【问题标题】:wpf binding label content to a sorted list entrywpf将标签内容绑定到排序列表条目
【发布时间】:2016-06-21 16:21:54
【问题描述】:

不确定这是否可能。我正在尝试将标签内容绑定到全局排序列表条目。

public class AppObj
{
  public static SortedList<string, string> Messages { get; set; }
  ......
}

AppObj.Messages = new SortedList<string, string>();
foreach (DictionaryEntry entry in entries)
{
  string key = entry.Key.ToString();
  string value = (string)entry.Value;
  if (AppObj.Messages.ContainsKey(key)) { AppObj.Messages.Add(key, value); }
  else { AppObj.Messages[key] = value; }
}

在xml中

<Label Content="{Binding AppObj.Messages["mykey"]}" />

[] 中的双引号会出错。

我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf c#-4.0


    【解决方案1】:

    使用IValueConverter。 SO 帖子here 显示了一个转换器,它为字典做了足够相似的工作。修改它以期望一个 SortedList,它看起来像这样:

    public class SortedListConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            SortedList<string, string> data = (SortedList<string, string>)value;
            String parame = (String)parameter;
            return data[parame];
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    将此添加到您的窗口资源中:

     <local:SortedListConverter x:Key="cvtr"/>
    

    然后像这样绑定:

    <Label Content="{Binding Source={StaticResource AppObj}, 
        Path=Messages,  
        Converter={StaticResource cvtr}, 
        ConverterParameter=key}" />
    

    【讨论】:

      【解决方案2】:

      如果示例中的mykey 是硬编码的键名,则只需创建一个属性,该属性将链接到键“mykey”的数据中。然后简单地绑定到该属性。

       public string ViewableMessage { return AppObj.Messages["mykey"]; }
      

      Xaml

       <Label Content="{Binding ViewableMessage }" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-13
        相关资源
        最近更新 更多