ComboBoxItem中的复选框绑定到类中的布尔值.如何从每个项目中获取每个布尔值



很抱歉我缺乏英语,请记住,我刚开始学习WPF,所以这可能不是最漂亮的方法。

我试图删除选中复选框的每个项目,但我有问题要指向复选框。所以我试图指向类中的布尔值。但也存在一些问题。然后我投降了,来到这里

如有任何帮助,我们将不胜感激

我的按钮应该从列表中删除选中复选框的某个项目,如下所示。

private void DeleteComboBoxItem_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < ComboBoxName.Items.Count; i++)
{
if (ComboBoxName.Item.Contains((CheckBox).Equals(True))) <--- Have Problems here.
{
List.RemoveAt(i);
}
}
}

只有猫的名字在列表中-我有一个公式可以添加猫的名字。

我有一个具有以下模板的组合框:

<ComboBox x:Name="ComboBoxName">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0" IsChecked="{Binding b_CheckBox}" VerticalContentAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding tb_Name}" />
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

还有一个类似的类。

public class Cat 
{
public bool b_Checkbox {get; set;}
public string tb_Name {get; set;}
}

希望你能帮助我。

您希望复选框触发移除cat,对吗?不知道,如果这是最有效的方式,但是,它工作

  1. 每次Cat类中的bool属性更改时添加一个事件:

    public class Cat 
    {
    public event Action<bool> CheckboxChanged;
    private bool imChecked;
    public bool ImChecked
    {
    get
    {
    return imChecked;
    }
    set
    {
    imChecked = value;
    CheckboxChanged?.Invoke(value);
    }
    }
    
    public string tb_Name { get; set; }            
    }     
    
  2. 在ViewModel中设置每次此事件触发时要执行的操作

//In the constructor of your ViewModel, iterate through each cat and subscribe to its event. Then, give the cats to the comboBox
public YourViewModel()
{
InitializeComponent();

//Getting the cats
ObservableCollection<Cat> Cats = new ObservableCollection<Cat>
{
new Cat () {tb_Name = "1st cat", ImChecked = false},
new Cat () {tb_Name = "2nd cat", ImChecked = false},
new Cat () {tb_Name = "3rd cat", ImChecked = false},
new Cat () {tb_Name = "4th cat", ImChecked = false},
};
//Subscribing to each cat's event
foreach (Cat cat in Cats)
{
cat.CheckboxChanged += CatChanged;
}
//Give the comboBox the cats
YourComboBox.ItemsSource = Cats;           
}

//This is what's gonna happen each time the ImChecked propierty in a cat changes
private void CatChanged(bool catIsChecked)
{
//Create a empty collection to add the cats that are not checked
ObservableCollection<Cat> catsToKeep = new ObservableCollection<Cat>();
//Grab the ones not checked
for (int i = 0; i < YourComboBox.Items.Count; i++)
{
Cat currentCat = YourComboBox.Items[i] as Cat;
if (currentCat.ImChecked == false)
{
catsToKeep.Add(currentCat);
}
}

//Give the unchecked cats to the comboBox again
YourComboBox.ItemsSource = catsToKeep;
}

Xaml:

<ComboBox x:Name="YourComboBox"
Height="30"
Width="150">

<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding ImChecked, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<TextBlock Text="{Binding tb_Name}"/>
</CheckBox>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

最新更新