我想在 C# 中创建一个没有内容但只有图像的按钮。
我不知道如何使用二传手。谁能赐教一下?
Setter setter = new Setter();
setter.Property = Image.SourceProperty;
setter.Value = "asd.jpg"; //<--error
Style Rstyle = new Style();
Rstyle.TargetType = typeof(Button);
Rstyle.Setters.Add(setter);
Button _Button = new Button()
{
Width = 41,
Height = 41
};
_Button.Style = Rstyle;
我应该在 setter.Value 中放置什么来获取驻留在项目目录中的图像。 “asd.jpg”
Button
有一个 Content
属性,您可以在其中转储一个 BitmapImage
:
BitmapImage image = new BitmapImage(new Uri("your source"));
TheButton.Content = image;
对于这个问题,Setters 不是必需的。 Setter 用于触发器和样式,无论是在 C# 还是在 XAML 中。
只需使用此代码。
BitmapImage bmp = new BitmapImage()
bmp.BeginInit();
bmp.UriSource = new Uri("pack://application:,,,/ApplicationName;component/Resources/myImage.png");
bmp.EndInit();
Image image = new Image();
image.Source = bmp;
myButton.Content = image;
<ControlTemplate x:Key="image"> //XAML in window resources tag
<Image Source="Save.png"/>
</ControlTemplate>
btn.Template = (ControlTemplate)FindResource("image");
我认为这样更灵活,可重复使用。