您提到的第一个解决方法可以在这里找到:将数据上下文字符串属性绑定到 StaticResource 键 https://stackoverflow.com/questions/695624/binding-a-datacontext-string-property-to-a-staticresource-key
我尝试使用你提到的第二个工作(http://sweux.com/blogs/psampaio/index.php/2009/06/16/using-data-binding-with-static-resources-in-wpf/ http://sweux.com/blogs/psampaio/index.php/2009/06/16/using-data-binding-with-static-resources-in-wpf/),但我从来没有让它工作过。由于 DataContext 为 null,因此它抛出了 ArgumentNullException。我认为这与我使用 DataTemplate 从 ViewModel 创建视图有关,并且在调用 ProvideValue 方法之前未设置 DataContext(在该页面的示例中,DataContext 设置为.xaml.vb 类)。
因此,我开始寻找一种解决方法,并找到了一种还涉及转换器的解决方法,但该方法通过 FrameworkElement 方法查找资源,而不是四处寻找 Application.Current。我找到的详细信息如下:
http://drwpf.com/blog/2007/08/18/can-my-value-converter-access-the-target-of-the-binding/ http://drwpf.com/blog/2007/08/18/can-my-value-converter-access-the-target-of-the-binding/
我把相关信息复制到这里:
它涉及实现接口 IMultiValueConverter 的 ValueConverter,以访问设置绑定的控件。
Convert方法的代码如下:
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
FrameworkElement targetObject = values[0] as FrameworkElement;
if (targetObject == null)
{
return DependencyProperty.UnsetValue;
}
return targetObject.TryFindResource(values[1]);
}
内容控件的 XAML 如下所示:
<ContentControl>
<ContentControl.Content>
<MultiBinding Converter="{StaticResource Converter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}" />
<Binding Path="ResourceKey" />
</MultiBinding.Bindings>
</MultiBinding>
</ContentControl.Content>
</ContentControl>
图像的 XAML 如下:
<Image Height="16" Width="16">
<Image.Source>
<MultiBinding Converter="{StaticResource Converter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}" />
<Binding Path="ResourceKey" />
</MultiBinding.Bindings>
</MultiBinding>
</Image.Source>
</Image>
工作起来就像一个魅力:D