2019-4-10-win10-uwp-自定义标记扩展

title author date CreateTime categories
win10 uwp 自定义标记扩展
lindexi
2019-04-10 09:46:13 +0800
2019-04-10 09:23:31 +0800
Win10 UWP

在 UWP 使用的 Binding 或 StaticResource 这些都是标记扩展,在 Windows 10 Fall Creators Update 版本号是 10.0.16299.0 和以上支持在 UWP 自定义标记扩展,也就是定义了一个可以在 xaml 使用的标记的方法

定义一个标记扩展需要满足下面条件

下面我简单写一个多语言支持的标记扩展,在界面使用多语言的时候我期望使用这个方式写多语言

        <TextBlock Text="{local:Lang Key=lindexi}" />

于是我需要创建多语言的类

    public class LangExtension : MarkupExtension

多语言返回的是字符串,所以标记 MarkupExtensionReturnTypeAttribute 同时设置返回的类

    [MarkupExtensionReturnType(ReturnType = typeof(string))]
    public class LangExtension : MarkupExtension

添加一个静态字典,用于存放多语言字符串

        public static Dictionary<string, string> LangList { set; get; } = new Dictionary<string, string>();

添加一个属性,用于绑定的时候输入,从上面代码可以知道我需要一个名为 key 的字符串属性

        public string Key { get; set; }

重写 ProvideValue 方法,根据用户输入的 Key 返回对应的多语言

        protected override object ProvideValue()
        {
            if (LangList.TryGetValue(Key, out var value))
            {
                return value;
            }

            return Key;
        }

整个 LangExtension 代码请看

    [MarkupExtensionReturnType(ReturnType = typeof(string))]
    public class LangExtension : MarkupExtension
    {
        public string Key { get; set; }

        protected override object ProvideValue()
        {
            if (LangList.TryGetValue(Key, out var value))
            {
                return value;
            }

            return Key;
        }

        public static Dictionary<string, string> LangList { set; get; } = new Dictionary<string, string>();
    }

此时就可以在 xaml 使用定义的标记扩展了

        <TextBlock Text="{local:LangExtension Key=lindexi}" />
        <TextBlock Text="{local:Lang Key=lindexi}" />

在使用的时候可以忽略 Extension 字符串

WindowsCommunityToolkit 也有两个定义,请看 OnDevice.csNullableBool.cs 如果有任何想法欢迎在 WindowsCommunityToolkit 讨论

本文使用的源代码放在 github 欢迎评论

Making the case for XAML Markup Extensions – pedrolamas.com

posted @ 2019-11-21 16:02  lindexi  阅读(75)  评论(0编辑  收藏  举报