C# 绑定WPF中的绑定
我有一个项目字典,我想在一个组合框中显示项目的一个方面——所有这些都是MVVM模式。在这方面,我将我的C# 绑定WPF中的绑定,c#,wpf,mvvm,binding,C#,Wpf,Mvvm,Binding,我有一个项目字典,我想在一个组合框中显示项目的一个方面——所有这些都是MVVM模式。在这方面,我将我的模型定义为: public class Model { public Dictionary<UInt32, string> samples { set; get; } } internal class ViewModel : INotifyPropertyChanged { public ViewModel() { var smpls = n
模型定义为:
public class Model
{
public Dictionary<UInt32, string> samples { set; get; }
}
internal class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
var smpls = new Dictionary<UInt32, string>();
smpls.Add(1, "one");
smpls.Add(2, "two");
models = new Dictionary<string, Model>();
models.Add("aKey", new Model() { samples = smpls });
key = "aKey";
}
private Dictionary<string, Model> _models;
public Dictionary<string, Model> models { set { _models = value; } get { return _models; } }
private string _key;
public string key { set { _key = value; OnPropertyChanged("key"); } get { return _key; } }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
然后我将模型
绑定到一个组合框,如下所示:
<Grid>
<ComboBox ItemsSource="{Binding Path=models[{Binding Path=key}].samples, Mode=OneTime}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Border>
<StackPanel>
<TextBlock Text="{Binding Path=Value}" />
</StackPanel>
</Border>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
而models[aKey].samples
是有效的,models[{Binding Path=key}]。samples
不是。您可能通过使用带有适当值转换器的
但是,创建一个附加的视图模型属性(如下图所示的CurrentSamples
属性)要容易得多,只要键
属性发生更改,该属性就会更新:
public Dictionary<UInt32, string> CurrentSamples
{
get { return models[key].samples; }
}
public string key
{
get { return _key; }
set
{
_key = value;
OnPropertyChanged("key");
OnPropertyChanged("CurrentSamples");
}
}
公共字典示例
{
获取{返回模型[key].samples;}
}
公共字符串密钥
{
获取{return\u key;}
设置
{
_键=值;
已更改的不动产(“密钥”);
OnPropertyChanged(“CurrentSamples”);
}
}
然后像这样绑定ItemsSource:
<ComboBox ItemsSource="{Binding CurrentSamples}">
...
</ComboBox>
...
我正在将models dictionary的键绑定到viewModel的键属性,但该属性不起作用
绑定通过反射到CLR结构中来工作。它通常使用Path
属性中的文本来查找CLR实例上的属性。模型[{Binding Path=key}]
不是进入结构的正确路径
它没有被编程为在绑定中搜索绑定;它将文本作为路径的文本
引用MSDN:
对于CLR属性,只要绑定引擎能够使用反射访问绑定源属性,数据绑定就可以工作
因此,第二个绑定(Path=models[aKey].samples
)之所以有效,是因为您提供了一个真实的路径位置以反映和绑定到。因此,基本上,我这样做在技术上是“不可能的”,我想最好的解决方法是Clemens建议的方法。@hamed我会考虑更改结构并使用源代码,我同意这是解决我的问题的最好办法,而且MVVM比我尝试的方式更简单。然而,我认为多重绑定在这里是一个不必要的重载;我认为你提出的方法是最简单的。
<ComboBox ItemsSource="{Binding CurrentSamples}">
...
</ComboBox>