ToggleButton/CheckBox content depending on its checked state?

▼魔方 西西 提交于 2020-01-02 04:27:06

问题


What's the shortest xamly way to make a ToggleButton contents depend on its checked state?

In WPF I'd probably go for a DataTrigger which doesn't exist in Silverlight.

I tried the following, but it doesn't work, as soon as I include the triggers, the binding to the source is broken. The triggers won't work anyway.

<ToggleButton
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
IsChecked="{Binding IsArchived, Mode=TwoWay}">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Checked">
      <ei:ChangePropertyAction
      TargetObject="{Binding
        RelativeSource={RelativeSource AncestorType=ToggleButton}}" 
      PropertyName="Content" Value="Unarchive project"/>
    </i:EventTrigger>
    <i:EventTrigger EventName="Unchecked">
      <ei:ChangePropertyAction 
      TargetObject="{Binding 
        RelativeSource={RelativeSource AncestorType=ToggleButton}}" 
      PropertyName="Content" Value="Archive project"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</ToggleButton>

回答1:


<ToggleButton Width="50" Height="50">
  <ToggleButton.Content>
        <TextBlock x:Name="obj" Text="Foo"/>
    </ToggleButton.Content>
  <i:Interaction.Triggers>
        <i:EventTrigger EventName="Checked">
            <ei:ChangePropertyAction PropertyName="Text" Value="On" TargetName="obj"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="Unchecked">
            <ei:ChangePropertyAction PropertyName="Text" Value="Off" TargetName="obj"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ToggleButton>



回答2:


I ended up using Kent Boogaart's converter, works great, and is also dependent on the bound property, not on a control trigger which might not fire at all (in a case where the property wasn't actually set), here is the code:

<ToggleButton.Content>
  <Binding Path="IsArchived"
    xmlns:boo="http://schemas.kent.boogaart.com/converters"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <Binding.Converter>
      <boo:MapConverter>
        <boo:Mapping To="Archive project">
          <boo:Mapping.From>
            <sys:Boolean>false</sys:Boolean>
          </boo:Mapping.From>
        </boo:Mapping>
        <boo:Mapping To="Unarchive project">
          <boo:Mapping.From>
            <sys:Boolean>true</sys:Boolean>
          </boo:Mapping.From>
        </boo:Mapping>
      </boo:MapConverter>
    </Binding.Converter>
  </Binding>
</ToggleButton.Content>


来源:https://stackoverflow.com/questions/9986727/togglebutton-checkbox-content-depending-on-its-checked-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!