[英]wpf binding label content to a sorted list entry
不确定这是可能的。 我试图将标签内容绑定到全局排序列表条目。
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; }
}
在xaml
<Label Content="{Binding AppObj.Messages["mykey"]}" />
[]内的双引号给出了错误。
我怎么能绕过这个?
使用IValueConverter 。 这里的SO帖子显示了一个转换器,它对Dictionary做了类似的工作。 修改它以期待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}" />
如果mykey
中的mykey
是硬编码的密钥名称,则只需创建一个属性,该属性将链接公开给密钥“mykey”的数据。 然后只需绑定到该属性。
public string ViewableMessage { return AppObj.Messages["mykey"]; }
XAML
<Label Content="{Binding ViewableMessage }" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.