【发布时间】: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