【问题标题】:How can I put default selected value in combobox in WPF MVVM如何将默认选定值放在 WPF MVVM 的组合框中
【发布时间】:2020-05-21 08:56:56
【问题描述】:

我在 WPF MVVM 中有一个组合框,我在组合框中有 3 个值。值是:A-B-全部 我想“全部”是组合框中的默认选择,我该怎么做?

我的 xaml 中的组合框:

<ComboBox  ItemsSource="{Binding Locations}" SelectedItem ="{Binding SelectedLocation}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="SelectionChanged">
                            <i:InvokeCommandAction Command="{Binding LocationFilterCommand}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </ComboBox>

我的视图模型中的位置可观察集合:

private ObservableCollection<string> _locations;
        public ObservableCollection<string> Locations
        {
            get { return _locations; }
            set
            {
                _locations = value;
                OnPropertyChanged("Locations");
            }
        }

        Locations = new ObservableCollection<string>()
        {
            "All","A","B"
        };

感谢您的所有帮助。

【问题讨论】:

  • 将默认值设置为SelectedLocation

标签: c# wpf mvvm combobox


【解决方案1】:

查看

<ComboBox
    ItemsSource="{Binding Locations}"
    SelectedItem="{Binding SelectedLocation}" />

ViewModel [使用 MVVMLight]

public class MainViewModel: ViewModelBase
{
    public MainViewModel()
    {
        SelectedLocation = Locations.First();
    }

    public IEnumerable<string> Locations => new[] {"All", "A", "B"};

    private string _selectedLocation;

    public string SelectedLocation
    {
        get => _selectedLocation;
        set
        {
            if (Set(nameof(SelectedLocation), ref _selectedLocation, value))
            {
                // Update location filter here
            }
        }
    }
}

没有必要为Locations 使用ObservableCollection,除非您计划在某个时候向集合中添加更多元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多