【发布时间】:2018-10-25 12:50:48
【问题描述】:
所以我创建了一个包含几个绑定复选框的组合框。我的 xml 看起来像这样:
<ComboBox x:Name="CbSandwichFilling" ItemsSource="{x:Bind SandwichFillingList}" PlaceholderText="Choose sandwich filling">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Name="{Binding Ingredient_name}" Content="{Binding Ingredient_name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我的 C# 看起来像这样:
private List<Ingredients> sandwichFilling;
public List<Ingredients> SandwichFillingList
{
get { return sandwichFilling; }
set { sandwichFilling = value; }
}
public BasicSandwiches()
{
sandwichFilling = Ingredients.GetIngredients("sandwichFilling");
this.DataContext = SandwichFillingList;
}
GetIngredients("sandwichFilling") 函数从数据库中接收三明治馅料并将它们放入 ComboBox 内的 Checkbox 中。
当用户按下按钮时,我希望程序知道哪些复选框被选中。我该怎么做?
【问题讨论】:
-
WPF、UWP 和 XAML 在设计时考虑了 MVVM 模式。虽然您可以使用其他方法,但这样做会失去大约 90% 的功能,并且在每个角落都会遇到问题。这看起来根本不像 MVVM。在 MVVM 模式中,inrgredients 将公开 Checkbox 也会绑定的“选定”属性,从而使答案变得微不足道(只需查看 bool 值)。几年前我写了一篇关于 MVVM 的简短介绍,但它仍然可以帮助你继续前进:social.msdn.microsoft.com/Forums/vstudio/en-US/…
-
理想情况下,您的成分类应该有一个 IsSelected 属性,您可以将其与 CheckBox 的 IsChecked 属性绑定。现在,当您单击按钮时,您只需遍历 SandwichFillingList 集合并检查哪些成分的 IsSelected 属性设置为 true。