WPF数据绑定到数据对象中的Dictionary
本文关键字:Dictionary 对象 数据 数据绑定 WPF | 更新日期: 2023-09-27 18:29:59
我有一个USER数据对象,它包含这样的字典:
public class User : INotifyPropertyChanged
{
private Dictionary<string, object> _metadata;
public Dictionary<string, object> Metadata
{
get { return this._metadata; }
set
{
this._metadata = value;
OnPropertyChanged("Metadata", value);
}
}
protected void OnPropertyChanged(string property, object value)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
我也有ViewModel由用户数据对象组成,如下所示:
public class ViewModel : INotifyPropertyChanged
{
public static ViewModel getInstance()
{
if (instance == null)
instance = new ViewModel();
return instance;
}
private User _user;
public User User
{
get { return this._user; }
set
{
this._user = value;
OnPropertyChanged("User", value);
}
}
protected void OnPropertyChanged(string property, object value)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
然后在我的主窗口中,我做了一些事情来在文本框和字典值(而不是字典键…)之间进行数据绑定
Binding myBinding = new Binding();
myBinding.Source = ViewModel.getInstance().User.Metadata;
myBinding.Path = new PropertyPath("SomeDictonaryKey");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(tb1, TextBox.TextProperty, myBinding));
但它不起作用,我尝试了不同的方法来更改binding.path
和binding.source
,它仍然不起作用。。。。
有人能告诉我出了什么问题吗????
您可以通过标准索引器语法绑定到字典值:
Binding myBinding = new Binding();
myBinding.Source = ViewModel.getInstance().User;
myBinding.Path = new PropertyPath("Metadata[SomeDictonaryKey]");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(tb1, TextBox.TextProperty, myBinding));
或者您可以使用source指定绑定源的所有路径:
myBinding.Source = ViewModel.getInstance().User.Metadata[SomeDictonaryKey];
myBinding.Path = new PropertyPath(".");
你可以在这里找到更多的例子。