如何将另一个DependencyProperty绑定到CheckBox的IsChecked属性?

8

这是我想要实现的一个例子:

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

当我尝试运行它时,出现了XamlParseException:

无法在类型为“Trigger”的“Property”属性上设置“Binding”。只能在DependencyObject的DependencyProperty上设置“Binding”。

那么,我该如何将ListBox的属性绑定到CheckBox的IsChecked属性呢?
1个回答

23

尝试使用DataTrigger。将您的Grid.Resources替换为以下内容,它就可以工作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接