繁体   English   中英

按钮内的图片和标签会在点击事件WPF上更新

[英]Image and label inside a button update on click event wpf

在Button buttonPlay包含StackPanel buttonPlay以使其内容丰富,例如

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

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

最简单的方法是为子控件设置名称,例如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";
     }
}

您应该给图像和标签命名,然后更新这两个源和内容。 您不应该更新内容按钮,因为它将替换所有的StackPanel,结果图像和标签全部消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM