天天看點

WPF中在XAML中實作資料類型轉換的兩種方法

原文: WPF中在XAML中實作資料類型轉換的兩種方法

熟悉資料綁定的朋友都知道,當我們在Model中擷取一個對象的資料,常常需要對其進行資料轉換後顯示在UI界面上,比如你用bool類型存儲了一個人的性别,但是在界面上卻需要經過轉化後顯示為男或女;

今天又把資料綁定部分又看了一下,在這裡就算是做個總結吧!

方法一:當我們定義一個類,該類中又有該類類型的一個屬性,那麼如果我們隻是在XAML中使用簡單的資料綁定的話,程式就會出現問題,究其原因就是程式無法正确對該類的對象的類類型的屬性無法正确轉化,是以我們需要自定義一個轉換類,該類繼承TypeConverter,并需要重寫一個該類的一個成員函數ConvertFrom,并且為需要進行轉換的類添加一個類型轉換的屬性,最後在XAML中進行靜态資源的使用就可以了!

相應類的示例代碼如下所示:

Human.cs

    [TypeConverterAttribute(typeof(ChildConverterToHuman))]
    public class Human
    {
        public string Name { get; set; }
        public Human Child { get; set; }
    }

    public class ChildConverterToHuman : TypeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            Human h = new Human();
            string str = value.ToString();
            h.Name = str;
            return h;
        }
    }
      
MainWindow.xaml    

    <Window.Resources>
        <local:Human x:Key="human" Name="hippie" child="tom"/>
    </Window.Resources>      

這樣我們就可以正确轉化Human對象的child的屬性的資料類型;

Human hu = this.FindResource("human") as Human;
if (hu != null)
{
     MessageBox.Show(hu.Name + hu.Child.Name);
}      

方法二:道理和方法一是一樣,依然需要定義一個類型轉換的類,但是需要繼承的類是IValueConverter類,需要我們重寫Convert和ConvertBack函數(一般重寫Convert就可以)

public class Person
    {
        public string Name { get; set; }
        public bool Gender { get; set; }
    }
    public class Converter : IValueConverter
    {
        /// <summary>
        /// Model TO UI
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool gender = (bool)value;
            if (gender == true)
            {
                return "男";
            }
            else
            {
                return "女";
            }
        }

        /// <summary>
        /// UI TO Model
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }      
<Window.Resources>
        <local:Converter x:Key="converter"/>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <StackPanel x:Name="sp" Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" FontSize="20" Margin="0,0,24,0"/>
                <TextBlock Text="{Binding Gender, Converter={StaticResource converter}}" FontSize="20"/>
            </StackPanel>
        </StackPanel>
    </Grid>      
Person p = new Person
 {
     Name = "Tom",
      Gender = false
 };
 sp.DataContext = p;      

這樣我們就可以将不同的資料類型通過一定的轉化顯示在程式界面上了!

繼續閱讀