【问题标题】:Insert image to Button Foreground将图像插入按钮前景
【发布时间】:2017-06-28 10:22:20
【问题描述】:

我想从代码中为 9 个按钮添加背景颜色和 9 个前景图像。 我希望从 C# 中更改图像,而不是在 WPF / xaml 中。 背景颜色可以使用:

button1.Background.SetValue(SolidColorBrush.ColorProperty, Windows.UI.Colors.Red);

Windows 窗体有一个简单的解决方案:

pictureBox1.Image = Properties.Resources.P1; // this does not work for UWP

到目前为止,我尝试过的内容都以错误消息告终: 我已将 P1.png 的 Build Action 属性从 Content 更改为 PRIResource,但没有成功。

string url = "../../Images/P1.png";
//string url = "PW.png";
image1.Source = new BitmapImage(new Uri(url, UriKind.Relative)); //.Uri cannot be converted into a Windows.Foundation.Uri.
//image1.Source = new BitmapImage(new Uri(url, UriKind.Absolute)); //format of url could not be determined
<Button x:Name="button1" Content="Button"  Grid.Column="0" Grid.Row="0"  
                Tag="1" Background="Gray" Padding="0" UseLayoutRounding="False"  
                HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Click="button1_Click">
    <Button.Foreground>
        <ImageBrush Stretch="Fill" ImageSource="P1.PNG"/>
    </Button.Foreground>
</Button>

【问题讨论】:

  • 您是否尝试过在代码中执行与在 xaml 中相同的操作? - 创建new ImageBrush(),设置它的ImageSource,然后附加到你的按钮上?
  • 你好罗马兹。你能告诉我一些关于如何设置 ImageSource 和附加按钮的示例代码吗?谢谢
  • 你好罗马兹。尝试以下但收到错误消息:Uri 无法转换为 Windows.Foundation.Uri ' ImageBrush imageBrush = new ImageBrush(); imageBrush.ImageSource = new BitmapImage(new Uri("Images/PW.PNG", UriKind.Relative)); button1.Foreground = imageBrush;'
  • 试一试:imageBrush.ImageSource = new BitmapImage(new Uri("ms-appx:///Images/PW.PNG"));

标签: c# visual-studio-2015 uwp windows-8.1


【解决方案1】:

解决方案: 在 C# 中使用 VS2015、UWP 和 Windows 8.1 将图像插入到 Button:

在按钮的前面添加一个图像。例如名称 = button1 和 imageX。 确保将 *.png 的“构建操作”属性设置为 Content。

enter code hereImageBrush imageBrush = new ImageBrush();
        imageBrush.ImageSource = new BitmapImage(new Uri("ms-appx:///Images/PW.PNG"));
        button1.Background = imageBrush;
 BitmapImage bitImage = new BitmapImage();
        bitImage.UriSource = new Uri("ms-appx:///Images/PW.PNG");
        imageX.Source = bitImage;

感谢 Romasz 的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多