WPF - Converting to multiple properties possible?
I have a textbox and a checkbox, i would like to set three properties on the textbox based on whether the checkbox is checked or not.
I can bind the properties to the checkbox but then i need to know what property is being bound in the converter.
For example, when unchecked i would like the textbox properties to be AcceptsReturn="False" TextWrapping="NoWrap" Height="25".
Then checked: AcceptsReturn="True" TextWrapping="Wrap" Height="100".
Will this require 3 converters or can i tell the converter "if checked==true && boundfrom == height, return 100"
Thanks, Kohan
Accepted Solution
<TextBox Name="txtAnswer" Margin="5" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden" >
<TextBox.Style>
<Style>
<Style.Triggers>开发者_高级运维;
<DataTrigger Binding="{Binding ElementName=cbMultiLine, Path=IsChecked}" Value="True">
<Setter Property="TextBox.TextWrapping" Value="Wrap" />
<Setter Property="TextBox.Height" Value="100" />
<Setter Property="TextBox.AcceptsReturn" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
This should work with one converter by using the ConverterParameter property on the binding:
Converter="{StaticResource MyIsCheckedConverter}" ConverterParameter="height"
The Converter would look like:
public class IsCheckedConverter : IValueConverter
{
public object Convert(
object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
object returnValue;
if (!((bool?)value).HasValue)
//do something if null (but I don't see why it would be)
switch ((string) parameter)
{
case "height":
returnValue = ((bool?)value).Value ? 100 : 25;
break;
case "TextWrapping":
.....
.....
}
return returnValue;
}
public object ConvertBack(
object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
//Likewise for convert back but I think in your case you wouldn't need to convert back
}
}
i would seriously consider using a data trigger. its a ui concern so i would try to avoid using your view model. you could do this with just a few lines of xaml.
<CheckBox x:Name="myCheckBox" />
<TextBox
AcceptsReturn="{Binding ElementName=myCheckBox, Path=IsChecked}"
TextWrapping="{Binding ElementName=myCheckBox, Path=IsChecked, Converter={StaticResource boolToTextWrappingConverter}}"
Height="{Binding ElementName=myCheckBox, Path=IsChecked, Converter={StaticResource boolToHeightConverter}}"
/>
this would reduce it to 2 converters. you could also write one boolToTextWrappingOrHeight
converter as you suggested in your post, and pass in a CommandParameter=height
and CommandParameter=textwrapping
and look at the parameter in the converter, but I'm not a fan of that approach. A third option would be to create IsChecked
, TextWrapping
and Height
properties in your viewmodel, bind to those, and put your conversion logic in the properties.
精彩评论