【问题标题】:How to bind a (static) Dictionary to Labels?如何将(静态)字典绑定到标签?
【发布时间】:2012-02-04 06:14:48
【问题描述】:

我有一个静态字典

class X { static Dictionary<string,string> MyDict {get { ... }} }

此词典包含我想在网格控件中显示的数据:

<Grid>
  <!-- Row and Column-Definitions here -->
  <Label Grid.Row="0" Grid.Column="0" Content="{Binding MyDict.Key=="foo" }" ToolTip="foo" />
  <!-- some more labels -->
</Grid>

1.) 我不知道如何(在 xaml 中)访问字典

2.) 我想将指定键的值绑定到标签的内容属性。

如何做到这一点?

【问题讨论】:

    标签: c# wpf binding dictionary


    【解决方案1】:

    要访问字典,您必须执行以下操作(如果您的 DataContext 还不是X 的实例):

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

    要访问字典中的值,您的绑定必须如下所示:

    <Label Content="{Binding MyDict[key]}" />
    

    【讨论】:

    • MyDict 是静态的,这种绑定能正常工作吗?拥有 X 的实例应该是不必要的。
    • 您需要一个实例来告诉绑定引擎您的类的类型,否则它将无法知道在哪里找到绑定目标。
    • 如果你可以看看我的回答,我认为应该可以达到预期的效果,而无需实例化 X 的实例。
    • 在这种情况下大写的 X 是什么?
    • @KalaJ:OP 想要访问其属性的类型。
    【解决方案2】:

    您的绑定将需要更改为以下内容:

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

    如果您查看 MSDN 中的 Binding Paths,您将看到可以在 XAML 中指定字符串索引器。 local 将是代表 X 所在命名空间的 xmlns。

    【讨论】:

    • 我能问你几个问题吗?本地是什么意思?我收到错误 The namespace prefix local is not defined 并且我假设的大 X 是我的列表存在的 ViewModel。
    【解决方案3】:

    您需要使用converter,这将允许您通过ConverterParameterDictionary 中提取您的价值。

    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];
        }
    }
    

    XAML 如下...

    <Window.Resources>
        <converters:DictConverter x:Key="MyDictConverter"/>
    </Window.Resources>
    
    Content="{Binding MyDictProperty, Converter={StaticResource MyDictConverter}, ConverterParameter=foo}"
    

    【讨论】:

    • 这完全是多余的,因为 XAML 解析器能够使用索引器。
    • @Tobias 这不是矫枉过正,而是关注点分离。
    • IMO 是这样,因为您正在创建一个类(带来的所有开销)只是为了模拟索引器访问,它已经内置。
    • 你应该分离的那些问题是什么?
    • @H.B.在 XAML 中键入知识。即使得到支持,恕我直言,感觉很骇人听闻。如果容器(字典)在路上发生变化,我可以调整我的单个转换器并完成。它将决策推到一个地方。
    【解决方案4】:

    我为转换器投票支持 Aaron,为索引器投票支持 Tobias,但要实际访问 静态字典,请尝试在实例级别复制属性并绑定到该属性

    // Code
    class X 
    { 
        protected static Dictionary<string,string> StaticDict { get { ... } } 
        public Dictionary<string, string> InstanceDict { get { return StaticDict; } } 
    } 
    
    // Xaml
    Content="{Binding InstanceDict, Converter = ... } "
    

    【讨论】:

    • 这不是必需的,因为您可以绑定到静态和实例属性,只要您的数据上下文是所需的类型。
    • @Tobias,我不知道,感谢您的澄清
    猜你喜欢
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    相关资源
    最近更新 更多