我有一个像这样的CheckBox设置:
<CheckBox Unchecked="checkBox_Unchecked">
<CheckBox.Style>
<Style TargetType="CheckBox">
<Setter Property="IsChecked" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding MyVal}" Value="{x:Null}">
<Setter Property="IsChecked" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
当我的Setter设置IsChecked = False时,有没有办法让Unchecked事件触发?
答案 0 :(得分:0)
这可能不是程序方法;但是对于你的陈述,我想我应该通过&#34; force&#34; ... 来指定你可以使用这个工作来做到这一点;
1)在你的ViewModel中有一个布尔属性,听取&#39; INotifyPropertyChanged&#39;
2)让property的默认值为true;
3)在构造函数中将属性的值重新分配给&#39; false&#39;。
4)这将触发未经检查的事件;
XAML:
<CheckBox IsChecked="{Binding CheckboxChecked}" Unchecked="ToggleButton_OnUnchecked"/>
C#:
public partial class MainWindow : INotifyPropertyChanged
{
private bool m_CheckboxChecked = true;
public bool CheckboxChecked
{
get { return m_CheckboxChecked; }
set { m_CheckboxChecked = value; OnPropertyChanged("CheckboxChecked"); }
}
public MainWindow()
{
DataContext = this;
InitializeComponent();
CheckboxChecked = false;
}
private void ToggleButton_OnUnchecked(object sender, RoutedEventArgs e)
{
Console.WriteLine("Un-Checked");
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
答案 1 :(得分:0)
你也需要一个案例IsChecked = false
的Setter。另外我建议绑定到ViewModel
中的命令试试这个:
<Style.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter Property="Command" Value="{Binding ElementName=this, Path=DataContext.ItemCheckedCommand}"></Setter>
</Trigger>
<Trigger Property="IsChecked" Value="false">
<Setter Property="Command" Value="{Binding ElementName=this, Path=DataContext.ItemCheckedCommand}"></Setter>
</Trigger>
</Style.Triggers>
并定义一个命令,让您在VM中拥有逻辑:
public RelayCommand ItemCheckCommand {get; private set;}