I am able to bind my datasource to the textblock for the display text. However I would like to set the Fontweight to bold if the value of the checkbox foo is checked. I'm trying to use IMultiValueConverter to accomplish this, but have had no luck so far. Any idea as to what I'm doing wrong?
<CheckBox Name="foo"/>
<TextBlock Name="bar" Text="{Binding Path=Name}">
<TextBlock.FontWeight>
<MultiBinding Converter="{StaticResource FontConverter}">
<Binding RelativeSource="{RelativeSource self}" Path="???"/>
<Binding ElementName="???" />
</MultiBinding>
</TextBlock.FontWeight>
</TextBlock>
and the converter class (just hardwired to always return bold for now)
Public Class FontConverter
Implements IMultiValueConverter
Public Function Convert(values() As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert
Return "Bold"
End Function
Public Function ConvertBack(value As Object, targetTypes() As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object() Implements System.Windows.Data.IMultiValueConverter.ConvertBack
Return nothing
End Function
End Class
If you want to use a converter you should bind to the CheckBox.IsChecked
( {Binding IsChecked, ElementName=foo}
), you do not need a MultiBinding
, then in Convert
cast the value
to bool
and based on that either return normal or bold (preferably as an actual FontWeight
, not a string
).
Here however i would recommend a DataTrigger on IsChecked
.
eg
<TextBlock Text="{Binding Name}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=foo}"
Value="true">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger >
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
(Also note dependency property precedence , if you set the FontWeight locally the trigger will no do anything)
Anything based on a condition in XAML should be done in a Trigger
or DataTrigger
. Converters
should be used when converting values from one value to another.
Here's an example:
<CheckBox Name="foo"/>
<TextBlock Name="bar" Text="{Binding Path=Name}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Normal" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=foo, Path=IsChecked}" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.