使用返回 StaticResource Primary 的转换器更改 xaml 中的颜色

问题描述 投票:0回答:1

如果我做一个这样的转换器

 public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
    if (value is null)
   
        return "Pink";
   
    else
        return "Red";
}

它工作正常,但如果我想返回“{StaticResource Primary}”或“StaticResource Primary”而不是粉红色或红色,它就不起作用

我的xaml是这样的

<Image Source="{FontImageSource FontFamily=MaterialRegular, Glyph={x:Static m:MaterialRegular.Folder}, Color={Binding Action, Converter={StaticResource ConvertColorFolder}}}" />`

你有什么想法吗?

.net xaml maui ivalueconverter
1个回答
0
投票

在毛伊岛,有些事情已经发生了变化。只需知道您无法直接访问应用程序级别的资源,它会引发异常,这就是我用来避免这种情况的方法:

public static class Extensions
{
    public static T GetResource<T>(this ResourceDictionary dictionary, string key)
    {
        if (dictionary.TryGetValue(key, out var value) && value is T resource)
            return resource;
        else
            return default;
    }
}

现在您需要使用此扩展方法在转换器中获取正确的颜色(不要忘记添加正确的命名空间):

public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
 {
   var primaryColor = Application.Current.Resources.GetResource<Color>("PrimaryColor");

   if (value is null)
    return primaryColor;
   else
    return Colors.Red;
}

请注意,这只是一个示例,需要根据您的需求进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.