通过键与字典项绑定 [英] Binding with dictionary item by key

查看:41
本文介绍了通过键与字典项绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些字典,我想将此字典中的项目绑定到某些控件,并想按项目键进行绑定.

Let's say I have some dictionary and I want to bind items from this dictionary to some controls and I want to bind by item key.

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        Dictionary<string,string> dictionary = new Dictionary<string,bool>();

        dictionary.Add("Item 1", "one");
        dictionary.Add("Item 2", "two");
        dictionary.Add("Item 3", "three");
        // ...
        dictionary.Add("Item 99", "ninety nine");

        // ...

        this.DataContext = //...
    }
}

XAML:

<Window ... >
    <Grid>
        <Label Content="{Binding ...}"/><!-- "Item 1" -->
        <TextBox Text="{Binding ...}"/><!-- "Item 3" -->

        <StackPanel>
             <CustomControl CustomProperty="{Binding ...}"/><!-- "Item 77" -->
             <CustomControl2 CustomProperty="{Binding ...}"/><!-- "Item 99" -->
        </StackPanel>
    </Window>

有可能吗?我该怎么办?

我想使用字典(或类似的东西).

I want to use dictionary (or something sililar).

我的带有变量的字典来自数据库,我有大约500个要绑定的变量.

My dictionary with variables comes from database and I have about 500 variables to bind.

这些变量不像人员列表"或类似的东西.它们具有非常不同的含义,我想将它们用作动态属性".

These variables are not like "list of persons" or something like that. They have very diffrent meaning and I want use them as "dynamic properties".

我需要将任何变量与任何控件的任何属性绑定.

推荐答案

<ItemsControl x:Name="dictionaryItemsControl" ItemsSource="{Binding dictionary}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

为此,您应该使字典"成为公共属性,并设置 this.DataContext = this; 或设置 dictionaryItemsControl.ItemsSource = dictionary;

For that you should make 'dictionary' public property, and set this.DataContext = this; or alternatively set dictionaryItemsControl.ItemsSource = dictionary;

这篇关于通过键与字典项绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆