W pierwszym kroku należy zdefiniować klasę implementującą interfejs IValueConverter.
public class DigitToBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { float res = 0; bool valid = float.TryParse(value.ToString(), out res); if(valid) { var props = typeof(Colors).GetProperties(); try { return new SolidColorBrush(Color.FromRgb((byte)res, 0, 0)); } catch (Exception) { return new SolidColorBrush(Color.FromRgb(0, 0, 0)); } } return Brushes.Wheat; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
Jeżeli interesuje nas binding w jedną stronę, metody ConvertBack nie trzeba implementować.
Następnie należy dodać do zasobów okna nasz konwerter.
<Window.Resources> <local:DigitToBrushConverter x:Key="myConverter" /> </Window.Resources>
Utworzona zostanie instancja konwertera, którą można przywoływać, jako StaticResource.
W końcu można przejść w xaml do stworzenia bindingu.
<Slider x:Name="colorSlider" /> <Button Background="{Binding ElementName=colorSlider, Converter={StaticResource myConverter}, Path=Value}" Content="BoundBackground" />
Dodatkową opcją jest ConverterParameter - obiekt, który będzie przekazany do metody konwertera.jako parameter.
Brak komentarzy:
Prześlij komentarz