【问题标题】:URI and a resource in xamlURI 和 xaml 中的资源
【发布时间】:2014-11-16 22:21:24
【问题描述】:

我有一个类作为视图的视图模型。该类有一个 ImageSource 类型的公共成员。现在我需要将属性类型更改为 uri(或字符串)。 但问题是我找不到使用 URI 从资源字典访问单个资源的方法。

例如目前我正在做这样的事情:

VectorResourcesDictionary = new ResourceDictionary();
Uri uri = new Uri("pack://application:,,,/assembly;component/IconResources.xaml", UriKind.Absolute);
VectorResourcesDictionary.Source = uri;
object rawResource = VectorResourcesDictionary["VectorIcon.LeftArrowIcon"];
return pickerSymbol = rawResource as ImageSource;

现在如何使用 URI 而不是 ImageSource 获得类似的结果?

【问题讨论】:

  • 我认为您以错误的方式执行 MVVM。与 UI 相关的图像、样式等应该属于 View 而不是 ViewModel。我建议您将其移至视图(xaml 文件。)
  • 是的,我知道错了,这就是为什么我必须将 ImageSource(ui 元素)更改为简单的字符串或 URI。问题是如何使用 URI 获取在 xaml 中定义的简单资源 ...

标签: wpf xaml resources uri imagesource


【解决方案1】:

很简单,只需将属性类型从ImageSource改为Uri即可:

public Uri PickerSymbol // i just guess the property name
{
    get
    {
        // get resource as string instead of ImageSource
        ...
        string uri = rawResource as string
        return new Uri(uri);
    }
}

在您的视图中保持与 PickerSymbol 属性的绑定,Uri 将自动转换为 ImageSource。

<Image Source="{Binding PickerSymbol}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多