将图像插入Button Foreground

时间:2017-02-10 06:48:01

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

我想从代码中添加背景颜色和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>

1 个答案:

答案 0 :(得分:0)

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

将图像添加到按钮的正面。例如Name = button1和imageX。 确保将* .png的“Build Action”属性设置为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的帮助。