刚学WPF不久,以下是测试的,老是选不到
<UserControl x:Class="HelloMvvmLight.ComboBoxWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:HelloMvvmLight"
DataContext="{Binding Source={StaticResource Locator},Path=Combo}"
mc:Ignorable="d"
Height="450" Width="800">
<StackPanel>
<Button x:Name="x" Command="{Binding GetDic}" Width="100" Height="30"> </Button>
<ComboBox Name="bo" Width="120" ItemsSource="{Binding Dic}" SelectedValue="{Binding SeValue,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" SelectedValuePath="Key" DisplayMemberPath="Value"></ComboBox>
</StackPanel>
</UserControl>
public class ComboBoxViewModel:ViewModelBase
{
public ComboBoxViewModel()
{
Dic = new Dictionary<string, string>();
selectValue = "0";
}
private Dictionary<string,string> dic;
public Dictionary<string,string> Dic
{
get { return dic; }
set
{
dic = value;
this.RaisePropertyChanged("Dic");
}
}
private string selectValue;
public string SeValue
{
get { return selectValue; }
set
{
selectValue = value;
this.RaisePropertyChanged("SeValue");
}
}
public RelayCommand GetDic => new Lazy<RelayCommand>(() => new RelayCommand(() =>
{
Dic.Add("0", "--请选择--");
Dic.Add("A", "A");
Dic.Add("B", "B");
Dic.Add("C", "C");
SeValue = "0";
})).Value;
}
绑定的容器最好实现INotifyCollectionChanged,这样WPF才能知道数据变化,在WPF中内置的容器是ObservableCollection<T>。
Dictionary类没有实现INotifyCollectionChanged接口,作为VM不太合适。
参考
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.5
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.inotifycollectionchanged?view=netframework-4.5
把Dictionary改成ObservableCollection就可以了,谢谢!