Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind another DependencyProperty to the IsChecked Property of a CheckBox?

Here's an example of what I'm trying to accomplish:

<Window x:Class="CheckBoxBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">

<StackPanel>
    <CheckBox Name="myCheckBox">this</CheckBox>    
    <Grid>
        <Grid.Resources>
            <Style TargetType="ListBox">
                <Style.Triggers>
                    <Trigger Property="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="True">
                        <Setter Property="Background" Value="Red" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <ListBox>
            <ListBoxItem>item</ListBoxItem>
            <ListBoxItem>another</ListBoxItem>
        </ListBox>
    </Grid>
</StackPanel>
</Window>

When I try to run it, I get this XamlParseException:

A 'Binding' cannot be set on the 'Property' property of type 'Trigger'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

So how can I bind a property on the ListBox to the IsChecked property of a CheckBox?

like image 911
Eben Geer Avatar asked May 26 '10 19:05

Eben Geer


1 Answers

Try using a DataTrigger. Replace your Grid.Resources with the following and it works:

    <Grid.Resources>
        <Style TargetType="ListBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="True">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Resources>
like image 198
Ben Collier Avatar answered Sep 23 '22 01:09

Ben Collier