The TextWrapping property of the TextBox has three possible values:
I would like to bind to the IsChecked property of a MenuItem. If the MenuItem is checked, I want to set the TextWrapping property of a TextBox to Wrap. If the MenuItem is not checked, I want to set the TextWrapping property of the TextBox to NoWrap.
To sum up, I am trying to bind a control that has two states to two values of an enumeration that has more than two values.
[edit] I would like to accomplish this in XAML, if possible.
[edit] I figured out how to do this using an IValueConverter. Perhaps there is a better way to do this? Here is what I did:
In Window.Resources, I declared a reference to my ValueConverter.
<local:Boolean2TextWrapping x:Key="Boolean2TextWrapping" />
In my TextBox, I created the binding to a MenuItem and included the Converter in the binding statement.
TextWrapping="{Binding ElementName=MenuItemWordWrap, Path=IsChecked, Converter={StaticResource Boolean2TextWrapping}}"
and the ValueConverter looks like this:
public class Boolean2TextWrapping : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
{
if (((bool)value) == false)
{
return TextWrapping.NoWrap;
}
return TextWrapping.Wrap;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
If you want to do this all in xaml you need to use a Style and a DataTrigger.
<StackPanel>
<CheckBox x:Name="WordWrap">Word Wrap</CheckBox>
<TextBlock Width="50">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin lacinia nibh non augue. Pellentesque pretium neque et neque auctor adipiscing.
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=WordWrap}" Value="True">
<Setter Property="TextWrapping" Value="Wrap" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With