<Window x:Class="WpfTutorialSamples.DataBinding.ConverterSample" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfTutorialSamples.DataBinding" Title="ConverterSample" Height="140" Width="250"> <Window.Resources> <local:YesNoToBooleanConverter x:Key="YesNoToBooleanConverter" /> </Window.Resources> <StackPanel Margin="10"> <TextBox Name="txtValue" /> <WrapPanel Margin="0,10"> <TextBlock Text="Current value is: " /> <TextBlock Text="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource YesNoToBooleanConverter}}"></TextBlock> </WrapPanel> <CheckBox IsChecked="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource YesNoToBooleanConverter}}" Content="Yes" /> </StackPanel> </Window>
using System; using System.Windows; using System.Windows.Data; namespace WpfTutorialSamples.DataBinding { public partial class ConverterSample : Window { public ConverterSample() { InitializeComponent(); } } public class YesNoToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { switch(value.ToString().ToLower()) { case "yes": case "oui": return true; case "no": case "non": return false; } return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if(value is bool) { if((bool)value == true) return "yes"; else return "no"; } return "no"; } } }
References
https://wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/