【问题标题】:How do i set the background image of a button in a WPF Application?如何在 WPF 应用程序中设置按钮的背景图像?
【发布时间】:2018-01-26 17:56:56
【问题描述】:

我在按钮的属性面板中找不到 background-Image 属性,我将解决方案根目录中每个按钮的图像存储为 Jpegs,该项目是 WPF,我不知道如何在 XAML 或 C# 代码中设置图像。我在 Visual Studio 2017 Community Edition 中开发

我之前看到的所有问题都是针对不同版本的Visual Studio,所以找不到答案

*edit - 我试图在设计时在 XAML 编辑器中更改按钮的背景图像,而不是创建 onclick 按钮来更改背景图像。所以如果我在 XAML 中有这个按钮:

<Button x:Name="keyBtn" 
        Content="Keyboard/Mouse" 
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Background="#FFB41717" 
        Margin="0,-31,0,0"/> 

我应该在“.background”属性中引用哪个部分?

【问题讨论】:

  • 您的意思是要在设计时使用 XAML 编辑器更改按钮背景?那么这行得通吗? How to change button background in WPF xaml?
  • 所以如果我在 xaml 中有这个按钮.. 我应该在“.background”属性中引用哪个部分?
  • 我不完全确定,但如果您可以 edit 您的问题来展示您迄今为止尝试过的内容(XAML 或 c#,视情况而定),我可以投票重新提出问题。

标签: c# wpf


【解决方案1】:

这可能比你想象的要容易..
将图像添加到项目后尝试此操作。

<Button x:Name="keyBtn" 
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Background="#FFB41717" 
        Margin="0,-31,0,0"> 
        <Image Source="myImage.png" />
</Button>

请注意,您需要删除内容,因为现在图像就是内容。

如果你也想要文本 - 你可以试试这个:

<Button x:Name="keyBtn" 
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Background="#FFB41717" 
        Margin="0,-31,0,0">
        <Grid>
            <Image Source="myImage.png" Stretch="Fill" />
            <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="Keyboard/Mouse" />
        </Grid>
</Button>

还有另一种选择 - 这可能正是您正在寻找的:

<Button x:Name="keyBtn" 
        Content="Keyboard/Mouse"
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Margin="0,-31,0,0">
        <Button.Background>
            <ImageBrush ImageSource="myImage.png" Stretch="Fill" />
        </Button.Background>
</Button>

但在最后一个选项中 - 您必须删除 Background 颜色,因为它正在被图像替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 2013-03-31
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多