IValueConverter值轉換器,可以將一種類型轉換為另一種類型,比如將值類型轉為字符串,將圖片url轉換為圖片類型,也可以將一個值進行計算轉換為新值等等。在WPF,一般在綁定的場合用的是比較多的。下面通過一個簡單的例子看看IValueConverter的用法。
首先,我們看IValueConverter有兩個方法:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture);
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture);
比如以我們最常見的頁碼轉換問題來看,一般進行分頁時,都是從0開始的,但是顯示是是要從第一頁顯示的。那么就可以使用轉換器來完成。
繼承IValueConverter接口:
public class PageIndexConvert:IValueConverter { public int AddValue { get; set; } public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int curentvalue = ToInt(value); curentvalue += AddValue; return curentvalue; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { int curentvalue = ToInt(value); curentvalue -= AddValue; return curentvalue; } public int ToInt(object value) { if (value == DBNull.Value || value == null || string.IsNullOrEmpty(value.ToString())) { return int.MinValue; } try { return System.Convert.ToInt32(value); } catch { return int.MinValue; } } }
界面使用寫好的轉換器:
<Window x:Class="TestConvert.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestConvert" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.Resources> <!--引用轉換器--> <local:PageIndexConvert x:Key="addoneconvert" AddValue="1"/> </Grid.Resources> <TextBox Height="52" HorizontalAlignment="Left" Margin="179,118,0,0" Name="textBox1" VerticalAlignment="Top" Width="152" KeyDown="NumberTextBox_KeyDown" /> <!--使用轉換器--> <TextBlock Height="44" HorizontalAlignment="Left" Margin="181,202,0,0" Name="textBlock1" Text="{Binding ElementName=textBox1, Path=Text,Converter={StaticResource addoneconvert}}" VerticalAlignment="Top" Width="150" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="105,132,0,0" Name="textBlock2" Text="輸 入:" VerticalAlignment="Top" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="105,202,0,0" Name="textBlock3" Text="轉 換:" VerticalAlignment="Top" /> </Grid> </Window>
效果圖:輸入數字后就轉換為指定的數值。
代碼下載:
http://download.csdn.net/detail/yysyangyangyangshan/5416169
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
