簡體   English   中英

如何將另一個DependencyProperty綁定到CheckBox的IsChecked屬性?

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

這是我想要完成的一個例子:

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

無法在“觸發器”類型的“屬性”屬性上設置“綁定”。 '綁定'只能在DependencyObject的DependencyProperty上設置。

那么如何將ListBox上的屬性綁定到CheckBox的IsChecked屬性?

嘗試使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM