C# wpf将标签内容绑定到已排序的列表项
我不确定这是否可行。我正在尝试将标签内容绑定到全局排序列表项C# wpf将标签内容绑定到已排序的列表项,c#,wpf,c#-4.0,C#,Wpf,C# 4.0,我不确定这是否可行。我正在尝试将标签内容绑定到全局排序列表项 public class AppObj { public static SortedList<string, string> Messages { get; set; } ...... } AppObj.Messages = new SortedList<string, string>(); foreach (DictionaryEntry entry in entries) { string k
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; }
}
公共类AppObj
{
公共静态分类列表消息{get;set;}
......
}
AppObj.Messages=new SortedList();
foreach(字典条目中的条目)
{
string key=entry.key.ToString();
字符串值=(字符串)entry.value;
if(AppObj.Messages.ContainsKey(key)){AppObj.Messages.Add(key,value);}
else{AppObj.Messages[key]=value;}
}
在xaml中
<Label Content="{Binding AppObj.Messages["mykey"]}" />
[]中的双引号给出错误
我怎样才能解决这个问题?使用。SO post显示了一个转换器,它为字典做了足够类似的工作。将其修改为预期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();
}
}
公共类SortedListConverter:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性)
{
SortedList数据=(SortedList)值;
字符串参数=(字符串)参数;
返回数据[参数];
}
公共对象转换回(对象值、类型targetType、对象参数、CultureInfo区域性)
{
抛出新的NotImplementedException();
}
}
将此添加到您的窗口资源:
<local:SortedListConverter x:Key="cvtr"/>
然后像这样绑定:
<Label Content="{Binding Source={StaticResource AppObj},
Path=Messages,
Converter={StaticResource cvtr},
ConverterParameter=key}" />
如果示例中的
mykey
是硬编码的密钥名称,则只需创建一个属性,该属性将链接公开到密钥“mykey”的数据中。然后简单地绑定到该属性
public string ViewableMessage { return AppObj.Messages["mykey"]; }
Xaml
<Label Content="{Binding ViewableMessage }" />