UWP如何获取ComboBox内绑定CheckBox的选中状态?
获取UWP ComboBox中选中的CheckBox项
嘿,这个需求其实挺典型的,核心思路是让你的数据模型和UI的选中状态双向绑定,这样完全不用去遍历UI元素找选中的CheckBox,直接从数据源里捞结果就行,下面一步步给你捋清楚:
第一步:给数据模型添加选中状态属性
你的Ingredients类需要新增一个IsSelected属性,并且实现INotifyPropertyChanged接口,这样UI的选中操作才能同步回数据源,代码如下:
public class Ingredients : INotifyPropertyChanged { public string Ingredient_name { get; set; } private bool _isSelected; public bool IsSelected { get => _isSelected; set { if (_isSelected != value) { _isSelected = value; OnPropertyChanged(nameof(IsSelected)); } } } // 实现INotifyPropertyChanged接口的必要代码 public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } // 保留你原有的GetIngredients方法 public static List<Ingredients> GetIngredients(string type) { // 你的数据库查询逻辑 } }
第二步:修改XAML里的CheckBox绑定
注意你原来的XAML里有个错误:CheckBox的Name属性不能绑定数据(Name是给后台代码引用UI元素用的,不能绑定数据对象的属性),得删掉这行。然后把IsChecked绑定到新增的IsSelected属性,并且指定双向绑定(UWP的x:Bind默认是单向的,所以要显式写Mode=TwoWay):
<ComboBox x:Name="CbSandwichFilling" ItemsSource="{x:Bind SandwichFillingList}" PlaceholderText="Choose sandwich filling"> <ComboBox.ItemTemplate> <DataTemplate x:DataType="local:Ingredients"> <CheckBox Content="{x:Bind Ingredient_name}" IsChecked="{x:Bind IsSelected, Mode=TwoWay}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
第三步:在按钮点击事件中获取选中项
先在XAML里加个按钮:
<Button Content="Get Selected Fillings" Click="GetSelectedFillings_Click" Margin="10"/>
然后在后台代码里实现点击事件,直接筛选数据源中IsSelected为true的项就行:
private void GetSelectedFillings_Click(object sender, RoutedEventArgs e) { // 筛选所有选中的馅料 var selectedFillings = SandwichFillingList.Where(ing => ing.IsSelected).ToList(); // 这里可以根据需求处理选中项,比如打印、展示等 foreach (var filling in selectedFillings) { System.Diagnostics.Debug.WriteLine($"选中的馅料:{filling.Ingredient_name}"); } }
小提示
你原来构造函数里的this.DataContext = SandwichFillingList;其实可以删掉,因为你用的是x:Bind,它默认绑定到页面的代码后台(也就是this),留着反而容易混淆。
这种方式遵循了MVVM的思想,代码更简洁,也比遍历UI元素找选中项的方式更可靠,毕竟UI元素的结构可能变化,但数据源是稳定的~
内容的提问来源于stack exchange,提问作者R. Verwilghen
相关产品推荐
相关产品推荐

