簡單介紹一下Wpf資源字典:
每個WPF界面元素都有一個名為Resource的屬性,這個屬性繼承至FrameworkElement類,其類型為ResourceDictionary。ResourceDictionary能夠以鍵值對的形式存儲資源,當要使用到某個資源的時候,使用鍵值對的形式獲取資源對象。在保存資源時,ResourceDictionary視資源對象為Object類型,所以再使用資源時先要對資源對象進行類型轉換,XAML編譯器能夠根據Attribute自動識別資源類型,如果類型不對就會拋出異常。
如果資源字典中存儲的是集合類型,而應用時只想取其中一個元素來綁定,這樣就需要自己編寫轉換器,來返回需要的元素值。
下面演示綁定集合中某元素例子:
首先定義集合內容:
1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 2 xmlns:sys="clr-namespace:System;assembly=mscorlib" 3 xmlns:syscollection="clr-namespace:System.Collections;assembly=mscorlib" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 5 <!--登錄界面--> 6 <syscollection:ArrayList x:Key="page_login"> 7 <syscollection:DictionaryEntry Key="title" Value="系統"/> 8 <syscollection:DictionaryEntry Key="login" Value="登錄"/> 9 <!--提示--> 10 <syscollection:DictionaryEntry Key="user_isnull" Value="用戶不能為空"/> 11 <syscollection:DictionaryEntry Key="password_isnull" Value="密碼不能為空"/> 12 <syscollection:DictionaryEntry Key="user_noexist" Value="用戶不存在"/> 13 <syscollection:DictionaryEntry Key="password_error" Value="密碼錯誤"/> 14 </syscollection:ArrayList> 15 16 </ResourceDictionary>
其次定義轉換器:
1 class CultureConverter : IValueConverter 2 { 3 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 4 { 5 if (value == null) return null; 6 ArrayList lst = value as ArrayList; 7 if (lst == null) return null; 8 Dictionary<object, object> dic = lst.Cast<DictionaryEntry>().ToDictionary(item => item.Key, item => item.Value); 9 if (dic.ContainsKey(parameter)) 10 return dic[parameter]; 11 else 12 return null; 13 } 14 15 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 16 { 17 throw new NotImplementedException(); 18 } 19 }
最后在Xaml中引用資源:
1 <!--定義轉換器資源--> 2 <Window.Resources> 3 <local:CultureConverter x:Key="CultureConverter"/> 4 </Window.Resources> 5 <!--在Xaml中引用資源--> 6 <Label Content="{Binding Converter={StaticResource CultureConverter}, ConverterParameter=title,Source={StaticResource page_login}}" Grid.Row="1" VerticalAlignment="Top" FontSize="36" FontWeight="Bold" Padding="0" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" />
注意:在Converter和Source中不可以引用DynamicResource。
應用資源轉換器可以靈活的實現資源的引用,尤其是分組資源。一個非常好的案例:國際化的應用。