WPF Setter类

时间:2012-06-19 13:10:43

标签: c# wpf expression

我想在c#中创建一个没有内容但只包含图像的按钮。

我不知道如何使用setter。谁能开导我?

            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”

3 个答案:

答案 0 :(得分:4)

Button有一个Content属性,您可以在其中转储BitmapImage

BitmapImage image = new BitmapImage(new Uri("your source"));
TheButton.Content = image;

答案 1 :(得分:1)

在c#代码中没有使用setter,它是在xamls中构建样式的辅助类。 只需使用此代码。

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;

答案 2 :(得分:0)

   <ControlTemplate x:Key="image"> //XAML in window resources tag
            <Image Source="Save.png"/>
   </ControlTemplate>


btn.Template =  (ControlTemplate)FindResource("image");

我认为这更灵活,可重复使用。