[原创]WPF资源Binding自定义集合类。

简单介绍一下Wpf资源字典:

每个WPF界面元素都有一个名为Resource的属性,这个属性继承至FrameworkElement类,其类型为ResourceDictionary。ResourceDictionary能够以键值对的形式存储资源,当要使用到某个资源的时候,使用键值对的形式获取资源对象。在保存资源时,ResourceDictionary视资源对象为Object类型,所以再使用资源时先要对资源对象进行类型转换,XAML编译器能够根据Attribute自动识别资源类型,如果类型不对就会抛出异常。

如果资源字典中存储的是集合类型,而应用时只想取其中一个元素来绑定,这样就需要自己编写转换器,来返回需要的元素值。

下面演示绑定集合中某元素例子:

首先定义集合内容:

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:syscollection="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--登录界面-->
<syscollection:ArrayList x:Key="page_login">
<syscollection:DictionaryEntry Key="title" Value="系统"/>
<syscollection:DictionaryEntry Key="login" Value="登录"/>
<!--提示-->
<syscollection:DictionaryEntry Key="user_isnull" Value="用户不能为空"/>
<syscollection:DictionaryEntry Key="password_isnull" Value="密码不能为空"/>
<syscollection:DictionaryEntry Key="user_noexist" Value="用户不存在"/>
<syscollection:DictionaryEntry Key="password_error" Value="密码错误"/>
</syscollection:ArrayList> </ResourceDictionary>

其次定义转换器:

 class CultureConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
ArrayList lst = value as ArrayList;
if (lst == null) return null;
Dictionary<object, object> dic = lst.Cast<DictionaryEntry>().ToDictionary(item => item.Key, item => item.Value);
if (dic.ContainsKey(parameter))
return dic[parameter];
else
return null;
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

最后在Xaml中引用资源:

     <!--定义转换器资源-->
<Window.Resources>
<local:CultureConverter x:Key="CultureConverter"/>
</Window.Resources>
<!--在Xaml中引用资源-->
<Label Content="{Binding Converter={StaticResource CultureConverter}, ConverterParameter=title,Source={StaticResource page_login}}" Grid.Row="" VerticalAlignment="Top" FontSize="" FontWeight="Bold" Padding="" Grid.ColumnSpan="" HorizontalContentAlignment="Center" />

注意:在Converter和Source中不可以引用DynamicResource。

应用资源转换器可以灵活的实现资源的引用,尤其是分组资源。一个非常好的案例:国际化的应用。

上一篇:LODOP打印控件之LODOP.NewPageA()方法


下一篇:20190421-那些年使用过的CSS预处理器(CSS Preprocessor)