简体   繁体   中英

Checked status not updated in CheckBox template

I'm trying to create an hyperlink that changes its text depending on a boolean value. I thought I could leverage the IsChecked method of a CheckBox. So I wrote this ControlTemplate for a CheckBox:

 <CheckBox Checked="CheckBox_Checked" IsChecked="{Binding Path=SomeBool, Mode=TwoWay}">
     <CheckBox.Template>
         <ControlTemplate TargetType="{x:Type CheckBox}">
             <BulletDecorator>
                <BulletDecorator.Bullet>
                    <TextBlock>
                        <Hyperlink>
                        <TextBlock x:Name="TextBoxHyperlink">Unchecked</TextBlock>
                        </Hyperlink>
                    </TextBlock>
                </BulletDecorator.Bullet>
                <ContentPresenter />
                </BulletDecorator>
                <ControlTemplate.Triggers>
                   <Trigger Property="IsChecked" Value="True">
                       <Setter TargetName="TextBoxHyperlink" 
                               Property="Text" 
                               Value="Checked" />
                   </Trigger>
               </ControlTemplate.Triggers>
            </ControlTemplate>
        </CheckBox.Template>
    </CheckBox>

But when I click on the hyperlink, nothing happens. The checked status is not changed and the Text property of the TextBlock is not updated. Any ideas?

By adding text in the TextBlock element as content, you're setting a local value on the Text property. Local values override values set by triggers, so your trigger will have no effect. See this StackOverflow question or Dependency Property Value Precedence on msdn.

If you set the Text property instead of adding it as content, it will be considered a parent template property set and be lower precedence than the parent template trigger:

<TextBlock x:Name="TextBoxHyperlink" Text="Unchecked"/>

Also, it sounds like you're only using a CheckBox because you want a trigger based on a Boolean property. You could use a DataTrigger instead of a Trigger to bind to a property on your DataContext instead of a property on your control, or you could just bind the Text property directly to SomeBool and use a value converter that converts true and false to "Checked" and "Unchecked".

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