绑定WPF属性(例如字典)



我正在寻找一种将代码中许多多余绑定压缩到单个词典中的方法。

在我的ViewModel中,我有一个字典:

 private Dictionary<string, bool> _myDict;
    public Dictionary<string, bool> MyDictionary
    {
        get
        {
            return _myDict;
        }
        set
        {
            _myDict = value;
        }
    }

非常简单。在正面,我希望能够将iSenabled绑定到字典条目。例如,如果我有KVP ("FirstBorder", false),那么我希望这个边框将ISENABLED设置为false

<Border Width="30" Height="25" IsEnabled="{Binding MyDictionary[FirstBorder]}">

此代码实际上无法使用 - 我正在寻找能够在字典中指定字符串键并根据其值设置属性的字符串键。甚至可能吗?

词典绝对是最糟糕的事情,因为多种原因,它是束缚的。最好使用实现InotifyPropertyChanged的自定义类型(集合中的TItem)使用键控。您将获得使用密钥访问值的好处,并且当值更改时属性更改通知。

,如果您真的想成为坏蛋,请在键控实现上实现InotifyCollectionCollection Changange。那会让'嫉妒。

我正在寻找能够在字典中指定字符串键并根据其值设置的字符串键。甚至可能吗?

是的,这应该有效:

public partial class MainWindow : Window
{
    private Dictionary<string, bool> _myDict;
    public Dictionary<string, bool> MyDictionary
    {
        get
        {
            return _myDict;
        }
        set
        {
            _myDict = value;
        }
    }
    public MainWindow()
    {
        InitializeComponent();
        _myDict = new Dictionary<string, bool>();
        _myDict.Add("FirstBorder", true);
        DataContext = this;
    }
}

<Button Content="Button" Width="30" Height="25" IsEnabled="{Binding MyDictionary[FirstBorder]}" />

确保在您试图启用/禁用的视图中,带有myDictionary属性的对象是该元素的数据。

edit:请注意,当您在运行时动态更新字典中的布尔值时,视图中元素的状态将不会动态更新并提高通知。

如果您愿意,您要么需要明确更新绑定:

_myDict["FirstBorder"] = true;
var be = button.GetBindingExpression(Button.IsEnabledProperty);
if (be != null)
  be.UpdateTarget();

...或与正确实现inotifyPropertychanged实现的类结合。

最新更新