我有几个复选框,我想要功能检查或取消选中所有复选框。这是一个类.cs和xaml代码。如何添加功能来检查或取消选中所有功能?
public static event PropertyChangedEventHandler IsCheckedChanged;
private bool isChecked;
public WorkStep(string name)
{
Name = name;
IsChecked = true;
}
public WorkStep(string name, bool isChecked)
{
Name = name;
IsChecked = isChecked;
}
public string Name
{
get;
}
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
OnIsCheckedChanged();
}
}
private void OnIsCheckedChanged()
{
PropertyChangedEventHandler handler = IsCheckedChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs("IsChecked"));
}
和xaml:
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
答案 0 :(得分:1)
我会使用INotifyPropertyChanged
界面,如下面所示:
public class myClass : INotifyPropertyChanged
{
private bool _IsChecked;
public bool IsChecked
{
get { return _IsChecked; }
set
{
_IsChecked = value;
OnPropertyChanged("IsChecked");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
然后我将属性IsChecked
绑定到我的所有复选框,如下面xaml所示:
<Grid>
<CheckBox x:Name="checkBox1" IsChecked="{Binding IsChecked,UpdateSourceTrigger=PropertyChanged}" Content="CheckBox" HorizontalAlignment="Left" Margin="116,90,0,0" VerticalAlignment="Top"/>
<CheckBox x:Name="checkBox2" IsChecked="{Binding IsChecked,UpdateSourceTrigger=PropertyChanged}" Content="CheckBox" HorizontalAlignment="Left" Margin="116,126,0,0" VerticalAlignment="Top"/>
<CheckBox x:Name="checkBox3" IsChecked="{Binding IsChecked,UpdateSourceTrigger=PropertyChanged}" Content="CheckBox" HorizontalAlignment="Left" Margin="116,164,0,0" VerticalAlignment="Top"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="380,235,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>
在MainWindow
类中创建IsChecked
属性所在类的新实例(在我的情况下为myClass MyClass = new myClass()
)。然后将新创建的实例MyClass
添加到MainWindow的DataContext(DataContext = MyClass;
)。我在这个例子中使用了一个按钮控件来检查和取消选中我的所有复选框。如果属性IsChecked
的值为true,则会检查所有复选框,如果错误,则取消选中所有复选框。 MainWindow
课程如下所示:
public MainWindow()
{
InitializeComponent();
DataContext = MyClass;
}
myClass MyClass = new myClass();
private void button_Click(object sender, RoutedEventArgs e)
{
if(MyClass.IsChecked)
MyClass.IsChecked = false;
else
MyClass.IsChecked = true;
}