首页 新闻 赞助 找找看

WPF MVVM ,点击加载时如何让ComboBox选择第一行

0
悬赏园豆:15 [已解决问题] 解决于 2021-06-30 12:05

刚学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;

  
}

风吹落叶的主页 风吹落叶 | 初学一级 | 园豆:67
提问于:2021-06-29 23:18
< >
分享
最佳答案
0

绑定的容器最好实现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

收获园豆:15
拓拓 | 小虾三级 |园豆:1050 | 2021-06-30 11:01

把Dictionary改成ObservableCollection就可以了,谢谢!

风吹落叶 | 园豆:67 (初学一级) | 2021-06-30 12:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册