如何将复选框的IsChecked属性的逆绑定到另一个复选框IsChecked属性 [英] How to bind a checkbox's inverse of IsChecked property to another checkbox IsChecked property

查看:213
本文介绍了如何将复选框的IsChecked属性的逆绑定到另一个复选框IsChecked属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将复选框的IsChecked属性的逆绑定到另一个复选框的IsChecked属性?

How to bind a checkbox''s inverse of IsChecked property to another checkbox IsChecked property?

推荐答案

您好,vivek,

这可以使用触发器在XAML本身中完成.

XAML:
将以下内容包含在Grid.Resources或Window

Hi vivek,

This can be done in XAML itself using Triggers.

XAML :
Include the below in Grid.Resources or in Window

<Style x:Key="ch" TargetType="CheckBox">
    <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=check2, Path=IsChecked}" Value="False">
            <Setter Property="IsChecked" Value="True"/>
        </DataTrigger>
    </Style.Triggers>
</Style>



并将此样式分配给复选框,以这种方式说出CheckBox1:



And assign this style to a checkbox, lets say CheckBox1 by doing in this way :

<checkbox name="check1" style="{StaticResource ch}" />



该触发器的作用是,它将检查Checkbox2的IsChecked属性的值.如果为假,则check1的IsChecked值将为true(就像您希望将其取反).

如果您不希望反转这些值,则可以通过执行以下操作在check1中立即将其向下:



What this trigger does is that, it will check the value of Checkbox2''s IsChecked property. If its false, then check1''s IsChecked value will be true(like you wanted it to be inversed).

If you don''t want the values to be inversed then, it can be down straight away in check1 by doing this :

<checkbox name="check1" ischecked="{Binding ElementName=check2, Path=IsChecked}" />



希望对您有所帮助!



Hope it helped!


如果您要绑定两个复选框,则完全无法达到此控件的目的.它旨在代表独立的选项.您正在尝试模仿单选按钮的行为.这不好!这样您的用户就会感到困惑.

—SA
If you want to bind two check boxes, you completely defeat the purpose of this control. It is designed to represent independent option. You''re trying to mimic behavior of radio button. This is bad! And your user will be confused.

—SA


另一种实现方法是扩展CheckBox类并重写checked属性以返回相反的值.像

Another way to do it is to extend the CheckBox class and override the checked property to return the inverse. Something like

class InverseCheckBox : CheckBox
    {
        new public bool Checked
        {
            get { return !base.Checked; }
            set { base.Checked = !value; }
        }

    }



我尚未严格测试此解决方案,并且不确定是否有任何副作用,但我希望有人会发现此方法有用:)



I haven''t rigorously tested this solution, and am unsure of any side effects, but I hope someone finds this useful :)


这篇关于如何将复选框的IsChecked属性的逆绑定到另一个复选框IsChecked属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆