Converter
De Banane Atomic
Aller à la navigationAller à la recherche
ValueConverter
<UserControl xmlns:my="clr-namespace:CurrentNameSpace"> <UserControl.Resources> <my:MyConverter x:Key="myConverter"/> </UserControl.Resources> <TextBlock Text="{Binding Path=., Converter={StaticResource ResourceKey=myConverter}}" /> |
namespace CurrentNameSpace { // L'attribut ValueConversion est optionel, // il permet de spécifier le type d'entrée et le type de sortie [ValueConversion(typeof(int), typeof(string))] public class MyConverter : IValueConverter { public object Convert(object values, Type targetType, object parameter, CultureInfo culture) { var binding1Value = (int)values; ... return ""; // un string } // Conversion inverse non-implémentée public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } |
Inverted convertion
BooleanToVisibilityConverter.cs |
public sealed class BooleanToVisibilityConverter : IValueConverter { public object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool visibleFlag = false; if (value is bool b) { visibleFlag = b; } else { return DependencyProperty.UnsetValue; } if (parameter != null) { if (Enum.TryParse(parameter.ToString(), true, out Parameters invert) && invert == Parameters.Inverted) { visibleFlag = !visibleFlag; } } return visibleFlag ? Visibility.Visible : Visibility.Collapsed; } public object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } private enum Parameters { Normal, Inverted } |
<TextBlock Visibility="{Binding MyProperty, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=Inverted}" /> |
MultiValueConverter
<UserControl xmlns:my="clr-namespace:CurrentNameSpace"> <UserControl.Resources> <my:MyConverter x:Key="myConverter"/> </UserControl.Resources> <TextBlock.Text> <MultiBinding Converter="{StaticResource ResourceKey=myConverter}"> <Binding ... /> <Binding ... /> </MultiBinding> </TextBlock.Text> |
namespace CurrentNameSpace { // L'attribut ValueConversion n'est pas utilisé ici car il n'est pas adapté // au MultiValueConverter : il ne peut définir qu'un seul type d'entrée public class MyConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var binding1Value = (int)values[0]; var binding2Value = (string)values[1]; ... return ""; // un string } // Conversion inverse non-implémentée public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } |