以编程方式在WPF中创建图像按钮

我想创建一个Windows工具栏(类似于RocketDock),它可以从序列化类中动态创建按钮,但我无法弄清楚如何动态设置图像。 另外,如何将图像序列化(我想用存储类序列化图像,而不是每次都从原始的png文件位置加载它)?

我找到了以下代码来创建依赖项属性

public class ImageButton { #region Image dependency property public static readonly DependencyProperty ImageProperty; public static ImageSource GetImage(DependencyObject obj) { return (ImageSource)obj.GetValue(ImageProperty); } public static void SetImage(DependencyObject obj, ImageSource value) { obj.SetValue(ImageProperty, value); } #endregion static ImageButton() { var metadata = new FrameworkPropertyMetadata((ImageSource)null); ImageProperty = DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ImageButton), metadata); } } 

我创建了一个按钮样式来inheritance以设置图像

               

但在创建按钮后,我无法弄清楚如何从代码中设置图像

 var newButton = new Button(); var style = (Style)FindResource("ImageButton"); 

newButton.Image无法解析。 我需要用style.Resources做点什么吗?


编辑 – 对奥利的回应

谢谢,但……使用……

 Link link = new Link(@"c:\temp\dev\ClearAllIcon.png"); var newButton = new Button(); newButton.Content = "bloberific"; var style = (Style)FindResource("ImageButton"); ImageButton.SetImage(newButton, link.IconSource); MainStack.Children.Add(newButton); 

其中链接定义为

 public Link(string iconPath) { IconPath = iconPath; IconSource = new BitmapImage(new Uri(iconPath)); } 

尽管文本有,但图像没有显示。 按钮看起来很正常。

您没有创建正常的依赖项属性,而是创建附加的依赖项属性。 您的newButton实例没有已定义的属性“Image”。 因此,您没有方便的CLR属性getter / setter(有关详细信息,请参阅MSDN )。

代码应与此类似,以设置图像源值:

 ImageButton.SetImage(newButton, imageSource); 
 Link link = new Link(@"c:\temp\dev\ClearAllIcon.png"); var newButton = new Button(); newButton.Content = "bloberific"; var style = (Style)FindResource("ImageButton"); ImageButton.SetImage(newButton, link.IconSource); MainStack.Children.Add(newButton); 

你不使用样式变量 – 这是问题吗?

这对我来说很有用,可以创造一个小游戏。

 var botao = sender as Button; Image i = new Image(); i.Source= new BitmapImage(new Uri(@"/Resources/x.png", UriKind.RelativeOrAbsolute)); botao.Content = i;