none
How to change image of toggle button at runtime?

    Question

  •  

    Hello friends,

     

    I would like to know as to how can I change the image of TOGGLE BUTTON at run time when we check the button? For example, I have kept the pic1.png in XAML and when the toggle button is checked I would like to change the toggle button image to pic2.png. And while unchecked, again revert back to pic1.png.

     

    Can any one please help me. Its urgent.

     

    Thanks.

    Monday, October 29, 2007 1:38 PM

Answers

  • Hi,

     

    You can use a Style trigger for this:

     

    Code Block

    <Window.Resources>

      <Image Source="DSC00040.JPG"

             x:Key="MyImage1" />

      <Image Source="DSC00041.JPG"

             x:Key="MyImage2" />

     

      <Style TargetType="{x:Type ToggleButton}"

             x:Key="MyToggleButtonStyle">

        <Setter Property="Content"

                Value="{DynamicResource MyImage1}" />

        <Style.Triggers>

          <Trigger Property="IsChecked"

                   Value="True">

            <Setter Property="Content"

                    Value="{DynamicResource MyImage2}" />

          </Trigger>

        </Style.Triggers>

      </Style>

    </Window.Resources>

    <Grid>

      <ToggleButton Style="{StaticResource MyToggleButtonStyle}" />

    </Grid>

     

     

    HTH,

    Laurent

    Monday, October 29, 2007 2:38 PM

All replies

  • Hi,

     

    You can use a Style trigger for this:

     

    Code Block

    <Window.Resources>

      <Image Source="DSC00040.JPG"

             x:Key="MyImage1" />

      <Image Source="DSC00041.JPG"

             x:Key="MyImage2" />

     

      <Style TargetType="{x:Type ToggleButton}"

             x:Key="MyToggleButtonStyle">

        <Setter Property="Content"

                Value="{DynamicResource MyImage1}" />

        <Style.Triggers>

          <Trigger Property="IsChecked"

                   Value="True">

            <Setter Property="Content"

                    Value="{DynamicResource MyImage2}" />

          </Trigger>

        </Style.Triggers>

      </Style>

    </Window.Resources>

    <Grid>

      <ToggleButton Style="{StaticResource MyToggleButtonStyle}" />

    </Grid>

     

     

    HTH,

    Laurent

    Monday, October 29, 2007 2:38 PM
  •  

    This was helpful to do in XAML. I was just wondering how to do the same in code behind.

    Tuesday, October 30, 2007 5:26 AM
  • Hi,

    Do you mean, how to add a Style to your button in code-behind, or how to handle the "Click" event of the ToggleButton in code-behind to change the content?

    Why do you want to do it in code-behind anyway? Any reason?

    Greetings,
    Laurent
    Tuesday, October 30, 2007 1:47 PM