轉帖|其它|編輯:郝浩|2011-03-25 16:05:25.000|閱讀 1126 次
概述:在前面的例子里,我們做了一個顯示滑塊進度的小程序: 在這里有一個小小的問題是,TextBox的Text屬性是string類型,而滑塊的Value應該是double類型。這里.net為我們自動的做了一類型轉換,但在一些復雜的邏輯中,就必須自定義一些Converter。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在前面的例子里,我們做了一個顯示滑塊進度的小程序:
在這里有一個小小的問題是,TextBox的Text屬性是string類型,而滑塊的Value應該是double類型。這里.net為我們自動的做了一類型轉換,但在一些復雜的邏輯中,就必須自定義一些Converter。
舉個很簡單的例子,我們在數據庫中存儲性別的時候一般會用bit類型,或男或女,雙性人估計現在還不是法律能容忍的。但是1/0值反映到前臺,就需要顯示為男/女,這里我們用到一個SexConverter來實現。
wpf通過繼承IValueConverter接口,并重寫Convert與ConverBack方法,顧名思義,這兩個方法一個是正向的,一個是反向,不過目前我還沒有遇到用上Back的機會。
代碼很簡單:
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>
后臺代碼:
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();
}
}
}
效果如圖:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網絡轉載