edgarmtze
edgarmtze

Reputation: 25058

Image and label inside a button update on click event wpf

Having a StackPanel inside a Button buttonPlay to make it rich content like

<Button Height="37" HorizontalAlignment="Left" Margin="222,72,0,0" Name="buttonPlay" Click="buttonPlay_Click">
  <StackPanel Orientation="Horizontal">
    <Image Source="play.jpg" Height="20" Width="27" />
    <Label Padding="4" Height="27" Width="55" FontWeight="Bold" FontFamily="Times New Roman"> Play</Label>
  </StackPanel>
</Button>

I would like the text inside the label and the image to change when I click the button, to do so inside buttonPlay_Click event I have and if else condition, However I do not know how to change the label nor image of it.

private void buttonPlay_Click(object sender, RoutedEventArgs e)
{
    if (buttonPlay.Content.ToString()  == "Play")
    {
        //....some actions
        buttonPlay.Content = "Stop";
    }
    else
    {
        //.....some other actions
        buttonPlay.Content = "Play";
    }
}

How to update label and image according to click?

Upvotes: 2

Views: 905

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39976

Give your Label and your Image a name. Like this:

<StackPanel Orientation="Horizontal" Name="hh">
    <Image  Height="20" Width="27" Name="img" Source="play.jpg" />
    <Label Padding="4" Height="27" Width="55" Name="lbl" FontWeight="Bold" FontFamily="Times New Roman">Play</Label>
</StackPanel>

private void buttonPlay_Click(object sender, RoutedEventArgs e)
{
     if (lbl.Content.ToString() == "Play")
     {
         //....some actions
         lbl.Content = "Stop";
         BitmapImage btm = new BitmapImage();
         btm.BeginInit();
         btm.UriSource = new Uri("pack://application:,,,/WpfApplication1;component/Resources/stop.png");
         btm.EndInit();
         img.Source = btm;
     }
     else
     {
         //.....some other actions
         lbl.Content = "Play";
     }
}

Upvotes: 2

Krikor Ailanjian
Krikor Ailanjian

Reputation: 1852

The easiest way to do this is to set names for the child controls such as buttonPlayImage and buttonPlayLabel, then you can access their properties with the . operator.

private void buttonPlay_Click(object sender, RoutedEventArgs e)
{
    if (buttonPlayLabel.Content == "Play")
    {
        buttonPlayLabel.Content = "Stop";

        buttonPlayImage.Source = new BitmapImage(new Uri("stop.png"));
    }
    else
    {
        //other actions
    }
}

And for names:

<Image Name="buttonPlayImage" ... />
<Label Name="buttonPlayLabel" ... >Play</Label>

Upvotes: 3

daniel
daniel

Reputation: 1070

You should give names to the Image and Label, then update these two Source and Content. You should not update the button Content as it will replace the all the StackPanel, result Image and Label all disappear.

Upvotes: 0

Related Questions