Customizing the toggle state of a toggle button in wpf

sudarsanyes picture sudarsanyes · Oct 7, 2009 · Viewed 44.5k times · Source

I wanna customize the toggle state of the toggle button in wpf. I want to set a image to the toggle button when it is on and set another image when it is off. TO do so, i thought of using triggers. This is how i ended up doing,

<Window ...>
    <Window.Resources>
        <Image x:Key="OnImage" Source="C:\ON.jpg" />
        <Image x:Key="OffImage" Source="C:\OFF.jpg" />
        <Style x:Key="OnOffToggleImageStyle" TargetType="ToggleButton">
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="{StaticResource OnImage}" />
                </Trigger>
                <Trigger Property="IsChecked" Value="False">
                    <Setter Property="Content" Value="{StaticResource OffImage}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                ...
                <ToggleButton IsChecked="{Binding Status}" Width="100" Height="35" Style="{StaticResource OnOffToggleImageStyle}" />
                ...
            </DataTemplate>
        </ListBox.ItemTemplate>
</Window>

The above snippet seems to works fine only for two items in the list box. If more than one item has the binding value, status to be true, it doesn't work (it works for only one such item). Please tell me whether I am proceeding in the correct direction. Also tell me other ways of achieving this.

Answer

Drew Noakes picture Drew Noakes · Oct 7, 2009

The issue here is because you are using Image resources. The Image in your resources is a concrete instance of a control. It can only be in one place at a time. So when you have more than one item in your list...

This should work for you:

<Style x:Key="OnOffToggleImageStyle" TargetType="ToggleButton">
 <Style.Triggers>
   <Trigger Property="IsChecked" Value="True">
     <Setter Property="Content">
       <Setter.Value>
         <Image Source="C:\ON.jpg" />
       </Setter.Value>
     </Setter>
   </Trigger>
   <Trigger Property="IsChecked" Value="False">
     <Setter Property="Content">
       <Setter.Value>
         <Image Source="C:\OFF.jpg" />
       </Setter.Value>
     </Setter>
   </Trigger>
 </Style.Triggers>
</Style>

Note that you can improve the performance of this by using an ImageSource for each image file in your resources, then referencing this in the Image. This effectively means that each image is only loaded once from disk, rather than 2*N times (where N is the number of items in your list.)