在单击事件wpf时更新按钮内的图像和标签

本文关键字:图像 标签 按钮 更新 单击 事件 wpf | 更新日期: 2023-09-27 18:07:49

在按钮buttonPlay中添加StackPanel,使其具有丰富的内容,如

<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>

我想在标签和图像内的文本改变,当我点击按钮,这样做在buttonPlay_Click事件我有,如果其他条件,但是我不知道如何改变它的标签和图像。

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

如何根据点击更新标签和图像?

在单击事件wpf时更新按钮内的图像和标签

最简单的方法是为子控件(如buttonPlayImagebuttonPlayLabel)设置名称,然后您可以使用.操作符访问它们的属性。

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
    }
}

对于名称:

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

LabelImage起个名字。这样的:

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

您应该给Image和Label命名,然后更新这两个Source和Content。你不应该更新按钮的内容,因为它会取代所有的StackPanel,结果图像和标签全部消失。