【问题标题】:UWP binding to custom dictionaryUWP 绑定到自定义字典
【发布时间】:2024-01-13 22:01:01
【问题描述】:

我有一个在 UWP 中工作的 ViewModel,除了我的自定义字典外,所有绑定都在工作,我不知道为什么。什么都没有显示。

我使用的是 FodyWeavers,因此使用了速记符号。如果未找到键,自定义字典将返回带有 * 的键。

在视图模型中

public static TranslationDictionary Translations { get; set; }

在视图中

 <TextBlock Text="{Binding Translations[Test_Translation]}" />

自定义词典

public class TranslationDictionary : Dictionary<string, string>
   {
       public new void Add(string key, string value)
       {
           if (value == null)
           {
               return;
           }
           base.Add(key, value);
       }

       public new void Remove(string key)
       {
           if (!ContainsKey(key))
           {
               return;
           }
           base.Remove(key);
       }

       public new string this[string key]
       {
           get
           {
               string value;
               return TryGetValue(key, out value) ? value : key + "*";
           }
           set
           {
               if (value == null)
               {
                   Remove(key);
               }
               else
               {
                   base[key] = value;
               }
           }
       }
   }

【问题讨论】:

    标签: c# uwp binding uwp-xaml


    【解决方案1】:

    您可以通过使用 x:Bind 而不是 Binding 来实现此结果

    x:Bind & Binding here的区别概览

    然后声明一个看起来像这样的静态类:

    public static class DictionariesOperations
    {
        public static string GetValue(Dictionary<string, string> dict, string key)
        {
            return dict[key];
        }
    }
    

    然后在你的 xaml 中:

    <TextBlock Text="{x:Bind local:DictionariesOperations.GetValue(Translations, Test_Translation)}" />
    

    希望这个帮助 =)

    【讨论】: