1.作用:可以將源數據和目標數據之間進行特定的轉化,
2.定義轉換器,需要繼承接口IValueConverter
[ValueConversion(typeof(int), typeof(string))] public class ForeColorConverter : IValueConverter { //源屬性傳給目標屬性時,調用此方法ConvertBack public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { int c = System.Convert.ToInt32(parameter); if (value == null) throw new ArgumentNullException("value can not be null"); int index = System.Convert.ToInt32(value); if (index == 0) return "Blue"; else if (index == 1) return "Red"; else return "Green"; } //目標屬性傳給源屬性時,調用此方法ConvertBack public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } }
public ValueConversionAttribute(Type sourceType, Type targetType):指定源屬性類型和目標屬性類型
Convert:會進行源屬性傳給目標屬性的特定轉化
ConvertBack:會進行目標屬性傳給源屬性的特定轉化
參數parameter:對應Binding的ConverterParameter屬性
3.使用轉換器
(1)引用轉換器所在的命名空間
xmlns:local1="clr-namespace:WpfTest.View"
(2)定義資源
<Window.Resources> <local1:ForeColorConverter x:Key="foreColor"></local1:ForeColorConverter> </Window.Resources>
(3)定義屬性
private int status = 0; public int Status { get => status; set { status = value; RaisePropertyChanged("Status"); } }
(4)綁定屬性,添加轉換器
<Grid>
<Label HorizontalAlignment="Left" Height="23" Margin="243,208,0,0" Content="這里哦" Foreground="{Binding Status,Converter={StaticResource foreColor},Mode=OneWay}" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="tbName" HorizontalAlignment="Left" Height="23" Margin="243,160,0,0" TextWrapping="Wrap" Text="{Binding Status,UpdateSourceTrigger=LostFocus,Mode=OneWayToSource}" VerticalAlignment="Top" Width="120"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="389,160,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
4.效果