轉(zhuǎn)帖|其它|編輯:郝浩|2011-03-25 16:05:25.000|閱讀 1126 次
概述:在前面的例子里,我們做了一個(gè)顯示滑塊進(jìn)度的小程序: 在這里有一個(gè)小小的問(wèn)題是,TextBox的Text屬性是string類型,而滑塊的Value應(yīng)該是double類型。這里.net為我們自動(dòng)的做了一類型轉(zhuǎn)換,但在一些復(fù)雜的邏輯中,就必須自定義一些Converter。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門(mén)軟控件火熱銷售中 >>
在前面的例子里,我們做了一個(gè)顯示滑塊進(jìn)度的小程序:
在這里有一個(gè)小小的問(wèn)題是,TextBox的Text屬性是string類型,而滑塊的Value應(yīng)該是double類型。這里.net為我們自動(dòng)的做了一類型轉(zhuǎn)換,但在一些復(fù)雜的邏輯中,就必須自定義一些Converter。
舉個(gè)很簡(jiǎn)單的例子,我們?cè)跀?shù)據(jù)庫(kù)中存儲(chǔ)性別的時(shí)候一般會(huì)用bit類型,或男或女,雙性人估計(jì)現(xiàn)在還不是法律能容忍的。但是1/0值反映到前臺(tái),就需要顯示為男/女,這里我們用到一個(gè)SexConverter來(lái)實(shí)現(xiàn)。
wpf通過(guò)繼承IValueConverter接口,并重寫(xiě)Convert與ConverBack方法,顧名思義,這兩個(gè)方法一個(gè)是正向的,一個(gè)是反向,不過(guò)目前我還沒(méi)有遇到用上Back的機(jī)會(huì)。
代碼很簡(jiǎn)單:
xaml代碼:
<Window x:Class="Data_Converter.SexConveter"
xmlns="//schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="//schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Data_Converter"
Title="SexConventer" Height="300" Width="300">
<Window.Resources>
<local:BitToSexConverter x:Key="Bts"></local:BitToSexConverter>
</Window.Resources>
<StackPanel x:Name="sp_List" Background="WhiteSmoke" Margin="5">
<ListBox Name="lb_List">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="5">
<CheckBox Margin="5"></CheckBox>
<TextBlock Text="{Binding Path=Name}" Width="80" Margin="5"/>
<TextBlock Text="{Binding Path=Sex, Converter={StaticResource Bts}}" Width="200" Margin="5"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
后臺(tái)代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Data_Converter
{
/// <summary>
/// SexConvet.xaml 的交互邏輯
/// </summary>
public partial class SexConveter : Window
{
public SexConveter()
{
InitializeComponent();
List<Student> lst = new List<Student>()
{
new Student(){Name="李雷",Sex=true},
new Student(){Name="韓梅梅",Sex=false},
new Student(){Name="Tom",Sex=true},
new Student(){Name="Lily",Sex=false},
};
this.lb_List.ItemsSource = lst;
}
public class Student
{
public string Name { get; set; }
public bool Sex { get; set; }
}
}
public class BitToSexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool sex = (bool)value;
if (sex) return "男";
else return "女";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
效果如圖:
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載