简体   繁体   中英

WPF bind enabled property of one control to a CheckBox

I am trying to bind the IsEnabled property of a control to the IsChecked property of a CheckBox using the following XAML, so the control will be enabled or disabled based on the CheckBox status.

<Setter Property="IsEnabled" Value="{Binding IsChecked, ElementName=aCheckBox, UpdateSourceTrigger=PropertyChanged}" />

It doesn't work. What is wrong?

EDIT: thanks for all your comments! below is from style.xaml, now based on @Ivan's comment. The TextBlock is set to "gray out" when disabled (taken from here )

<Style x:Key="printCkBox" TargetType="CheckBox">
    <Setter Property="LayoutTransform">
        <Setter.Value>
            <ScaleTransform ScaleX="2" ScaleY="2"/>
        </Setter.Value>
    </Setter>
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>

<Style x:Key="fileInfoTxtBlkBase" TargetType="TextBlock">
    <Setter Property="TextWrapping" Value="NoWrap"/>
    <Setter Property="FontSize" Value="20"/>
    <Setter Property="Padding" Value="2"/>
    <Setter Property="IsEnabled" Value="{Binding ElementName=printCkBox, Path=IsChecked, NotifyOnSourceUpdated=True}"/>
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{StaticResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </Style.Triggers>
</Style>

<Style x:Key="filenameTxtBlk" BasedOn="{StaticResource fileInfoTxtBlkBase}" TargetType="TextBlock">
    <Setter Property="TextAlignment" Value="Left"/>
</Style>

Though it's an old question, but still here's an answer to the original question in the title for someone else, stumbling here like I did:

<DockPanel>
        <CheckBox x:Name="CbxAgree" Content="Agreed" FontSize="21" 
                  Background="Black" Foreground="Black"
                  VerticalAlignment="Center" Margin="8 4 16 4"
                  IsChecked="True" />

        <Button VerticalAlignment="Stretch" 
                Background="White" Foreground="Black" 
                Content="Submit"  FontSize="22"
                IsEnabled="{Binding ElementName=CbxAgree, Path=IsChecked}"/>
</DockPanel>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM