How to bind a (static) Dictionary to Labels?

后端 未结 4 1002
自闭症患者
自闭症患者 2021-01-19 05:57

I have a static Dictionary

class X { static Dictionary MyDict {get { ... }} }

This Dictionary contains Data i want to

相关标签:
4条回答
  • 2021-01-19 06:25

    Your binding will need to change to be the following:

    Content="{Binding Path=[foo], Source={x:Static local:X.MyDict}}"
    

    If you look at Binding Paths from the MSDN, you will see that string indexers can be specified in XAML. local will be the xmlns representing the namespace X resides in.

    0 讨论(0)
  • 2021-01-19 06:26

    I voted up Aaron for the converter and Tobias for indexers, but to actually access the static dictionary, try duplicating the property at the instance level and binding to that

    // Code
    class X 
    { 
        protected static Dictionary<string,string> StaticDict { get { ... } } 
        public Dictionary<string, string> InstanceDict { get { return StaticDict; } } 
    } 
    
    // Xaml
    Content="{Binding InstanceDict, Converter = ... } "
    
    0 讨论(0)
  • 2021-01-19 06:34

    To get access to the Dictionary, you have to do something like this (if your DataContext isn't already an instance of X):

    <Grid>
        <Grid.DataContext>
            <X xmlns="clr-namespace:Your.Namespace" />
        </Grid.DataContext>
        <!-- other code here -->
    </Grid>
    

    To access the values in the dictionary, your binding has to look as follows:

    <Label Content="{Binding MyDict[key]}" />
    
    0 讨论(0)
  • 2021-01-19 06:41

    You need to use a converter which will allow you to extract your value out of the Dictionary via the ConverterParameter.

    public class DictConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Dictionary<string,string> data = (Dictionary<string,string>)value;
            String parameter = (String)parameter;
            return data[parameter];
        }
    }
    

    The XAML would be as follows...

    <Window.Resources>
        <converters:DictConverter x:Key="MyDictConverter"/>
    </Window.Resources>
    
    Content="{Binding MyDictProperty, Converter={StaticResource MyDictConverter}, ConverterParameter=foo}"
    
    0 讨论(0)
提交回复
热议问题