[英]CheckBox.AutoCheck in wpf
What is the easiest alternative of making checkBox.AutoCheck
= false
in WPF? 在WPF
checkBox.AutoCheck
= false
的最简单方法是什么? Specifically prevent CheckBox from changing IsChecked on click . 特别是防止CheckBox 在点击时更改IsChecked 。
CheckBox
should still react on clicks ( Command
and/or InputBindings
), but shouldn't try to change its visual state on left click or Space key. CheckBox
仍应对点击 ( Command
和/或InputBindings
) 做出反应 ,但不应尝试在左键单击或Space键上更改其可视状态。
I can prevent bound property change by using Mode=OneWay
, but this seems have no effect on visual state, CheckBox
then become checked while my property is false
, which makes me sad... 我可以通过使用
Mode=OneWay
来防止绑定属性更改,但这似乎对视觉状态没有影响, CheckBox
然后在我的属性为false
被检查,这让我很难过......
Here is an example of checkbox: 这是一个复选框的示例:
<!-- make this checkbox behave as if AutoCheck = false -->
<CheckBox IsChecked="{Binding IsChecked, Mode=OneWay}"
Command="{Binding CommandLeftButtonOrSpace}">
<CheckBox.InputBindings>
<MouseBinding MouseAction="RightClick"
Command="{Binding CommandRightButton}" />
</CheckBox.InputBindings>
</CheckBox>
A simple attached behavior will do 一个简单的附加行为就可以了
public class CheckBoxBehavior
{
public static bool GetDisableAutoCheck(DependencyObject obj) => (bool)obj.GetValue(DisableAutoCheckProperty);
public static void SetDisableAutoCheck(DependencyObject obj, bool value) => obj.SetValue(DisableAutoCheckProperty, value);
public static readonly DependencyProperty DisableAutoCheckProperty =
DependencyProperty.RegisterAttached("DisableAutoCheck", typeof(bool),
typeof(CheckBoxBehavior), new PropertyMetadata(false, (d, e) =>
{
var checkBox = d as CheckBox;
if (checkBox == null)
throw new ArgumentException("Only used with CheckBox");
if ((bool)e.NewValue)
checkBox.Click += DisableAutoCheck_Click;
else
checkBox.Click -= DisableAutoCheck_Click;
}));
private static void DisableAutoCheck_Click(object sender, RoutedEventArgs e) =>
((CheckBox)sender).IsChecked = !((CheckBox)sender).IsChecked;
}
Setting like this 像这样设置
<ComboBox local:CheckBoxBehavior.DisableAutoCheck="True" ... />
You can prevent it from toggling in the first place by subclassing the control (from another answer ): 您可以通过继承控件(来自另一个答案 )来防止它首先切换:
public class OneWayCheckBox : CheckBox
{
private class CancelTwoWayMetadata : FrameworkPropertyMetadata
{
protected override void Merge(PropertyMetadata baseMetadata, DependencyProperty dp)
{
base.Merge(baseMetadata, dp);
BindsTwoWayByDefault = false;
}
}
static OneWayCheckBox()
{
// Remove BindsTwoWayByDefault
IsCheckedProperty.OverrideMetadata(typeof(OneWayCheckBox), new CancelTwoWayMetadata());
}
protected override void OnToggle()
{
// Do nothing.
}
}
This also switches the binding type of IsChecked
so that you don't need to remember to put Mode=OneWay
on it. 这也会切换
IsChecked
的绑定类型,因此您无需记住将Mode=OneWay
置于其上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.