绑定到资源密钥WPF [英] Binding to resource key, WPF
问题描述
我有一个带有一些图像的ResourceDictionary:
I have a ResourceDictionary with some images:
<BitmapImage UriSource="..\Images\Bright\folder-bright.png"
x:Key="FolderItemImage" />
我为树状视图项目创建了HierarchicalTemplate
,如下所示:
I've create a HierarchicalTemplate
for treeview items like the following:
<HierarchicalDataTemplate ItemsSource="{Binding VisibleChildren}"
DataType="{x:Type st:StructureTreeItem}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ImageResourceKey}" />
<Image x:Name="iIcon2" Source="{DynamicResource FolderItemImage}"/>
<Image x:Name="iIcon"
Source="{DynamicResource {Binding ImageResourceKey}}"/>
</StackPanel>
</HierarchicalDataTemplate>
现在,当显示项目时:
- 文本块显示
FolderItemImage
- 显示第一张图片
- 未显示第二张图片.
整个想法是将项目图像设置为存储在资源中的图像,但是不幸的是,上面介绍的技术无效,现在我知道了,为什么:
The whole idea is to set item images to ones stored in resources, but the technique presented above unfortunately won't work and now I know, why:
<Image x:Name="iIcon3" Width="16" Height="16" Margin="0, 1, 3, 1" >
<Image.Source>
<DynamicResource ResourceKey="{Binding ImageResourceKey}" />
</Image.Source>
</Image>
结果:
PresentationFramework.dll中发生了'System.Windows.Markup.XamlParseException'类型的未处理异常
An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
其他信息:不能在类型为"DynamicResourceExtension"的"ResourceKey"属性上设置"Binding".只能在DependencyObject的DependencyProperty上设置绑定".
Additional information: A 'Binding' cannot be set on the 'ResourceKey' property of type 'DynamicResourceExtension'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
因此,我必须重新表述我的问题:如何将存储在模型中的某些数据(也许是资源密钥?)转换为动态资源?它必须是动态资源,因为我敢肯定它可能会在运行时更改.
So I have to rephrase my question: how can I convert some data (a resource key, perhaps?) stored in model to a dynamic resource? It has to be a dynamic resource, because I'm certain it may change during runtime.
推荐答案
不能直接完成.但是,还有另一种涉及附加属性的方法:
It cannot be done directly. There's another way though involving an attached property:
public static class ImageHelper {
private static void SourceResourceKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var element = d as Image;
if (element != null) {
element.SetResourceReference(Image.SourceProperty, e.NewValue);
}
}
public static readonly DependencyProperty SourceResourceKeyProperty = DependencyProperty.RegisterAttached("SourceResourceKey",
typeof(object),
typeof(ImageHelper),
new PropertyMetadata(String.Empty, SourceResourceKeyChanged));
public static void SetSourceResourceKey(Image element, object value) {
element.SetValue(SourceResourceKeyProperty, value);
}
public static object GetSourceResourceKey(Image element) {
return element.GetValue(SourceResourceKeyProperty);
}
}
然后:
<Image local:ImageHelper.SourceResourceKey="{Binding SomeValue}" />
这篇关于绑定到资源密钥WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!