Question

I am trying to bind the ItemsSource of my ComboBox to a static dictionary I have on a static class.

In WPF I would use the following which would work fine:

ItemSource="{x:Static objectModel:LocaleHelper.FriendlyNames}"

Where LocaleHelper is the class name and FriendlyNames is the dictionary property of which I wish to bind to.
However in Silverlight I get an error to do with the type x:Static not being found.
Could anyone explain to me what the issue is and the workaround?
I have looked around but couldn't find any detailed explanations.
Sorry if this is a simple issue - I'm new to Silverlight and also WPF in general.

EDIT: After having done some more reading it looks like silverlight does not support static resources. Furthermore Dictionaries do not seem to update property changed / support DisplayMemberPath & SelectedValue so having the dictionary as a field in my viewmodel doesn't seem to be an option either.

Was it helpful?

Solution

You can only bind to non-static public properties (not fields). But you can use any "carrier" for those properties (so you are not forced to have those properties in the ViewModel). Let's see...

<Resources>
    <LocaleHelperWrapper x:Key="Wrapper"/>
</Resources>

<ComboBox ItemsSource="{Binding Path=FriendlyNames,
                                Source={StaticResource Wrapper}}"/>

And the wrapper code:

public class LocaleHelperWrapper
{
    public Dictionary<string, string> FriendlyNames
    {
        get { return LocaleHelper.FriendlyNames; }
    }
}

[Edit] The ComboBox supports DisplayMemberPath and SelectedValue. Assuming you want to use the ComboBox to select the Key and display the Value of you Dictionary's KeyValuePairs:

<ComboBox
    DisplayMemberPath="Value"
    SelectedValuePath="Key"
    SelectedValue="{Binding Path=MySelectionViewModel.SelectedKey, Mode=TwoWay}"
    ItemsSource="..."/>

OTHER TIPS

If it's merely an issue of binding to a collection, you might as well do it in the constructor of the ViewModel. Further consider using an ObservableCollection in case your static collection changes over time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top