wpf - 样式以更改对话框中按钮上的图像
问题描述
我无法让以下工作,我一定缺少一些基本的东西。我的目标是在对话框(窗口)上有一种样式,以便在其中的按钮上设置图像。所以我在对话框代码中添加了一个 DependencyProperty,如下所示:
public static readonly DependencyProperty ImageRefreshProperty =
DependencyProperty.Register(nameof(ImageRefreshProperty), typeof(ImageSource),
typeof(MyDlg), new PropertyMetadata(new BitmapImage(
new Uri(@"pack://application:,,,/component/Resources/refresh.png"))));
public ImageSource ImageRefresh {
get { return (ImageSource)GetValue(ImageRefreshProperty); }
set { SetValue(ImageRefreshProperty, value); }
}
在 Xaml 我有这个:
<Button DockPanel.Dock="Left" Style="{StaticResource buttonIcon}">
<Image Source="{Binding Path=ImageRefresh,
RelativeSource={RelativeSource AncestorType=local:MyDlg}}" />
</Button>
只要我使用代码来更改图像,这就可以正常工作,例如
dlg.ImageRefresh = new BitmapImage(
new Uri("pack://application:,,,/component/Resources/refr.png"));
但理想情况下,我想通过一种样式设置图像,如下所示:
<Style TargetType="{x:Type MyDlg}">
<Setter Property="ImageRefresh" Value="pack://application:,,,/component/Resources/refr.png" />
</Style>
我得到的错误是:
System.Windows.Markup.XamlParseException:
''Provide value on 'System.Windows.StaticResourceExtension' threw an exception.'
Inner Exception System.Windows.Markup.XamlParseException:
ArgumentNullException: Key cannot be null. Arg_ParamName_Name
我还尝试了一个在其中定义 BitmapImage 而不是字符串的 Setter Value,但我仍然遇到相同的错误:
<Setter Property="ImageRefresh">
<Setter.Value>
<BitmapImage UriSource="pack://application:,,,/component/Resources/refr.png"/>
</Setter.Value>
</Setter>
为 DependencyProperty 的 getter/setter 设置断点甚至不会被命中,在 Image 的 Source 的绑定上的 Converter 也不会。
我在这里想念什么?
编辑:为了查看 ImageSource 是否与它有关,我用另一个 bool 类型的属性测试了我的代码?在对话框中设置按钮的 IsEnabled 属性,但结果是一样的。所以错误不在于图像,它的包 URL(顺便说一句),但显然与其他东西有关。
解决方案
在我的代码中进行了一些挖掘之后,我自己找到了答案。问题是 DependencyProperty 的定义。我的代码有:
public static readonly DependencyProperty ImageRefreshProperty =
DependencyProperty.Register(nameof(ImageRefreshProperty) /*Wrong*/,
typeof(ImageSource),
typeof(MyDlg), new PropertyMetadata(new BitmapImage(
new Uri(@"pack://application:,,,/component/Resources/refresh.png"))));
但应该是:
public static readonly DependencyProperty ImageRefreshProperty =
DependencyProperty.Register(nameof(ImageRefresh) /*Correct*/,
typeof(ImageSource),
typeof(MyDlg), new PropertyMetadata(new BitmapImage(
new Uri(@"pack://application:,,,/component/Resources/refresh.png"))));
一个很小的疏忽会带来很大的后果......