【问题标题】:button image changing按钮图像更改
【发布时间】:2012-06-17 15:11:31
【问题描述】:

我想在用户每次按下按钮时更改按钮的背景图像。 我已将 ImageSource 设置为我的图片。当鼠标悬停在按钮上时,我的按钮不显示图像。如何设置图片,即使鼠标悬停按钮仍然有图片?

        <Button x:Name="recordButton" Content="" HorizontalAlignment="Left" Height="50" Margin="60,45,0,0" VerticalAlignment="Top" Width="50" Click="recordButton_Click">
        <Button.Background>
            <ImageBrush ImageSource="play.png"/>
        </Button.Background>
    </Button>

还有一个问题。这两张图怎么改? 它们的名称是“play.png”和“stop.png”,都位于资源中。

        private bool recordStarted = false;

    private void recordButton_Click(object sender, RoutedEventArgs e)
    {
        recordStarted = !recordStarted;


        if(recordStarted)
        {
            ImageBrush brush1 = new ImageBrush();
            BitmapImage image = Properties.Resources.stop;
            brush1.ImageSource = image;
            recordButton.Background = brush1;

        }
    }

我试过了,但是 VS 找不到 BitmapImage image = Properties.Resources.stop; 请帮忙!

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    我建议不要将背景设置为图像,而是将内容设置为图像

    <Button x:Name="recordButton" HorizontalAlignment="Left" Height="50" Margin="60,45,0,0" VerticalAlignment="Top" Width="50" Click="recordButton_Click">
        <Image Source="play.png"/>
    </Button>
    

    如果要更改图像,可以在文本中执行此操作,最简单的方法是使用编译为资源的图像而不是资源文件中的图像

    (recordButton.Content as Image).Source = new BitmapImage(new Uri("Images/stop.png", UriKind.Relative));
    

    如果你想使用资源文件,看这个SO post

    【讨论】:

    • 嗯。但是改变图片有什么帮助呢?
    • 谢谢。但是......现在按下按钮后它不再显示任何图像。所以它没有帮助:(
    • 确保“Images/stop.png”是您的图片的正确位置,并且它被设置为编译为资源(项目属性)
    【解决方案2】:

    换图有几种方法:

    1. 重新定义按钮控件模板并使用VisualStateManager

    2. 重新定义控件模板,使用Triggers。

    3. 您可以尝试将按钮的内容绑定到它的MouseOver 属性:鼠标悬停时隐藏一个图像并显示另一个图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多