c# - 如何使用 ListView /组合框 uwp 设置默认选定项

标签 c# combobox win-universal-app

我希望 ComboBox 有一个默认的选定值,在这种情况下它将是 View 模型中的第一个项目。

<ComboBox  Name="cat_choices" ItemsSource="{x:Bind ViewModel.Categories}" Width="300" VerticalAlignment="Center">
    <ComboBox.ItemTemplate>
        <DataTemplate x:DataType="local:Category">                            
            <TextBlock  Text="{x:Bind cat_name}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

来自 View 模型:

private ObservableCollection<Category> categories = new ObservableCollection<Category>();
public ObservableCollection<Category> Categories { get { return this.categories;  } }

谢谢。

最佳答案

在您的 ViewModel 中创建 2 个新属性:

private int _SelectedIndex = 0;

    public int SelectedIndex 
    {
        get
        {
            return _SelectedIndex;
        }
        set
        {
            _SelectedIndex = value;
            RaisePropertyChanged(nameof(SelectedIndex));
        }
    }

private Category _SelectedQuality = null;
    public Category SelectedQuality
    {
        get
        {
            return _SelectedQuality;
        }
        set
        {
            _SelectedCategory = value;
            RaisePropertyChanged(nameof(SelectedCategory ));
        }
    }

完成类别填充后,设置 SelectedCategory = Categories.First();

在 xaml 中,将 ComboBox 的 SelectedIndexSelectedItem 属性绑定(bind)到 ViewModel 中新创建的属性,设置绑定(bind)模式 = 两种方式。

关于c# - 如何使用 ListView /组合框 uwp 设置默认选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970947/

相关文章:

winapi - 所有者绘制组合框的垂直尺寸大于非所有者绘制组合框的垂直尺寸

c# - 更改禁用文本框的颜色

c# - MVVM轻掷(您是否忘记了调用> NavigationService.Configure?参数名称: pageKey) exception

C# 网络流 getString 方法

c# - 为方法发出代码时取消装箱可为 Nullable 使评估堆栈处于意外(对我而言)状态

c# - C# 的多线程和并发

c# - UWP 覆盖样式属性而不丢失其他属性定义

c# - 如果我有一个重复次数的数字,我如何重复一个字符来组成一个字符串?

java - ComboBox 未在 JTable 中显示其内容

java - 组合框以用户友好的方式获取数据并将其设置为数字