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?
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>
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";
}
}
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.
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.