Click here to Skip to main content
15,900,907 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
How to bind a checkbox's inverse of IsChecked property to another checkbox IsChecked property?
Posted

Hi vivek,

This can be done in XAML itself using Triggers.

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

XML
<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>


And assign this style to a checkbox, lets say CheckBox1 by doing in this way :
XML
<checkbox name="check1" style="{StaticResource ch}" />


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 :

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


Hope it helped!
 
Share this answer
 
Comments
Henry Minute 1-Mar-11 10:10am    
Good answer.
Tarun.K.S 1-Mar-11 11:47am    
Thanks!
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
 
Share this answer
 
Comments
vivektp 1-Mar-11 23:15pm    
i am sorry..i have a checkbox and a togglebutton actually
Sergey Alexandrovich Kryukov 2-Mar-11 0:01am    
Same thing.
--SA
Sergey Alexandrovich Kryukov 2-Mar-11 3:06am    
I don't care how you vote, the idea is bad, not acceptable. Who is loosing, anyway?
--SA
Another way to do it is to extend the CheckBox class and override the checked property to return the inverse. Something like

C#
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 :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900