WPF Binding值轉換器ValueConverter使用簡介(一)


WPF、Silverlight及Windows Phone程序開發中往往需要將綁定的數據進行特定轉換,比如DateTime類型的時間轉換為yyyyMMdd的日期,再如有一個值是根據另外多組值的不同而異的,此時我們就需要定制自己的Converter。

.Net Framework提供了兩種Converter接口,單值轉換的接口IValueConverter和多值轉換的接口IMultiValueConverter,它們都屬於System.Windows.Data命名空間,在程序集PresentationFramework.dll中。這兩種值轉換器都是分區域性的。其中方法Convert和ConvertBack都具有指示區域性信息的culture參數。如果區域性信息與轉換無關,那么在自定義轉換器中可以忽略該參數。

一、單值轉換實例,IValueConverter

1.當值從綁定源傳播給綁定目標時,調用方法Convert

2.當值從綁定目標傳播給綁定源時,調用此方法ConvertBack,方法ConvertBack的實現必須是方法Convert的反向實現。

    /// <summary>
    /// 自定義事件轉換
    /// </summary>
    public class TimeConver : IValueConverter
    {
        //當值從綁定源傳播給綁定目標時,調用方法Convert
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return DependencyProperty.UnsetValue;
            DateTime date = (DateTime)value;
            return date.ToString("yyyy-MM-dd");
        }
        //當值從綁定目標傳播給綁定源時,調用此方法ConvertBack
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = value as string;
            DateTime txtDate;
            if (DateTime.TryParse(str, out txtDate))
            {
                return txtDate;
            }
            return DependencyProperty.UnsetValue;
        }
    }

注:返回值DependencyProperty.UnsetValue表示轉換器沒有生成任何值。

在xaml中引用TimeConver的命名空間

xmlns:local="clr-namespace:AudioDemo.View"

在xaml中定義Resources

<Window.Resources>
    <local:TimeConver x:Key="cvtDate"/>
</Window.Resources>

在xaml重指定Binding值使用自定義Converter轉換

<TextBox x:Name="textBox" Text="{Binding ElementName=dateOne,Path=SelectedDate,Converter={StaticResource cvtDate}}" 
                 HorizontalAlignment="Left" 
                 Height="23" Margin="85,105,0,0" 
                 TextWrapping="Wrap" VerticalAlignment="Top" Width="183"/>

Xaml文件內容:

<Grid>
    <DatePicker x:Name="dateOne"  
                HorizontalAlignment="Left" Margin="85,50,0,0" VerticalAlignment="Top" Width="183"
                SelectedDateFormat="Long"/>
    <TextBox x:Name="textBox" Text="{Binding ElementName=dateOne,Path=SelectedDate,Converter={StaticResource cvtDate}}" 
                HorizontalAlignment="Left" 
                Height="23" Margin="85,105,0,0" 
                TextWrapping="Wrap" VerticalAlignment="Top" Width="183"/>
    <Label x:Name="label" Content="選擇結果:" HorizontalAlignment="Left" Margin="19,105,0,0" VerticalAlignment="Top"/>

    <Label x:Name="label1" Content="{Binding ElementName=dateOne,Path=Text}" 
            HorizontalAlignment="Left" Margin="85,145,0,0" VerticalAlignment="Top"/>
</Grid>

運行結果:

使用轉換前:               使用自定義Converter轉換后:

更多參考:

WPF Binding值轉換器ValueConverter使用簡介(二)-IMultiValueConverter


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM