我希望 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 的 SelectedIndex
和 SelectedItem
属性绑定(bind)到 ViewModel 中新创建的属性,设置绑定(bind)模式 = 两种方式。
关于c# - 如何使用 ListView /组合框 uwp 设置默认选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970947/