如何通过更改通知绑定到词典项? [英] How to make binding to dictionary item with change notification?

查看:99
本文介绍了如何通过更改通知绑定到词典项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="{Binding Dic[foo]}" />
        <Button Content="test" Click="Button_Click" />
    </StackPanel>
</Window>

和后备代码:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public Dictionary<string, string> Dic { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Dic = new Dictionary<string, string>();
            Dic.Add("foo", "bar");
            DataContext = this;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Doesn't work :(
            Dic["foo"] = "YEAH!";
        }
    }
}

在这里 TextBlock 可以正确地绑定到字典项 foo,但是当值改变时如何使其更新?

Here TextBlock properly binds to dictionary item "foo". But how to make it to update when its value is changed?

推荐答案

您需要使用 Binding.IndexerName 作为属性名称,您可能希望将其封装在继承或管理字典

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

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