通过键与字典项绑定

2024-04-07

假设我有一些字典,我想将该字典中的项目绑定到某些控件,并且我想通过项目键进行绑定。

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>

是否可以?我该怎么做?

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

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

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

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


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

为此,您应该将“字典”设为公共财产,并设置this.DataContext = this;或者设置dictionaryItemsControl.ItemsSource = dictionary;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过键与字典项绑定 的相关文章

随机推荐