【发布时间】:2010-11-24 20:33:45
【问题描述】:
我想创建一个从序列化类动态创建按钮的 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);
}
}
我创建了一个按钮样式来继承来设置图像
<Style x:Key="ImageButton" TargetType="{x:Type Button}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Image Source="{Binding Path=(Extender:ImageButton.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"
HorizontalAlignment="Left" Margin="8,0,0,0" Height="16" Width="16" />
<TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" />
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
但我不知道如何在创建按钮后从代码中设置图像
var newButton = new Button();
var style = (Style)FindResource("ImageButton");
newButton.Image 无法解析。我需要对 style.Resources 做些什么吗?
编辑 - 对 Olli 的回应
谢谢,但是...使用...
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));
}
图像不显示,但文本显示。按钮外观正常。
【问题讨论】:
标签: c# wpf button c#-4.0 dynamic