复选框.自动检查在wpf
本文关键字:wpf 检查 复选框 | 更新日期: 2023-09-27 18:17:27
在WPF中制作checkBox.AutoCheck
= false
的最简单的替代方案是什么?特别防止CheckBox从改变IsChecked点击。
CheckBox
应该仍然反应点击 (Command
和/或InputBindings
),但不应该试图改变其视觉状态左键或空格键。
我可以通过使用Mode=OneWay
来防止绑定属性的改变,但这似乎对视觉状态没有影响,CheckBox
然后成为检查,而我的属性是false
,这让我很伤心…
下面是一个复选框的例子:
<!-- 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>
你可以首先通过子类化控件(从另一个答案)来防止它切换:
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.
}
}
这也切换了IsChecked
的绑定类型,这样你就不需要记住把Mode=OneWay
放在上面了。
一个简单的附加行为就可以了
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;
}
像这样设置
<ComboBox local:CheckBoxBehavior.DisableAutoCheck="True" ... />