2016-12-06 104 views
0

我正在寻找一种方法来将我的代码中的很多多余的绑定压缩到单个字典中。绑定WPF属性,如IsEnabled到字典

在我的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]}"> 

此代码不实际工作 - 我在寻找什么,我必须做能够在Dictionary中指定一个字符串Key,并根据其值设置属性。它甚至有可能吗?

回答

1

词典绝对是最糟糕的事情,因为一些不同的原因而被绑定。更好地使用KeyedCollection针对执行INotifyPropertyChanged的自定义类型(集合中的TItem)。您可以获得使用密钥访问值的好处,并在值更改时获得属性更改通知。

如果您真的想成为笨蛋,请在您的KeyedCollection实现上实现INotifyCollectionChanged。这会让他们嫉妒。

0

我正在寻找我必须要做的事情,以便能够在字典中指定字符串键并根据其值设置属性。它甚至有可能吗?

是的,这应该工作:

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属性的对象是在视图中的元素,您正试图启用/禁用的DataContext的。

编辑:注意,在视图元素的状态将不会动态更新,当您在运行时动态更新词典中的布尔值,因为字典类不实现INotifyPropertyChanged接口,并提出更改通知。

如果你想要这个你要么需要更新明确的结合:

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

...或结合正确实施的INotifyPropertyChanged的一类。

+0

它不需要某个UpdateProperty吗? – Skyl3lazer

+0

我不确定你的意思。你打算从UI中更新词典中的值还是什么? – mm8

+0

该值在整个程序中适当更新。使用如图所示的代码实际上并没有实际更新IsEnabled标志。 – Skyl3lazer