开发者

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

开发者 https://www.devze.com 2023-01-01 17:33 出处:网络
Here\'s an example of what I\'m trying to accomplish: <Window x:Class=\"CheckBoxBinding.MainWindow\"

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?


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

精彩评论

暂无评论...
验证码 换一张
取 消