我有一个条目的字典,我想在组合框中展示其中的一些方面,并且要使用MVVM模式。为此,我定义我的Model
如下:
public class Model
{
public Dictionary<UInt32, string> samples { set; get; }
}
我的 ViewModel
如下:
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));
}
}
}
然后,我将models
绑定到下拉框中,代码如下:
<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
字典的键绑定到viewModel
的key
属性上,但不起作用。然而,如果我按照以下方式更改代码,一切都正常:
<ComboBox ItemsSource="{Binding Path=models[aKey].samples, Mode=OneTime}">