Reputation: 140
I have a requirement where text block should turn red,bold,underline and font should become bigger while validating on save button.
Below is my xamlcode
<TextBlock HorizontalAlignment="Right"
Foreground="{x:Bind Model.FirstNameError, Converter={StaticResource ErrorColorConverter}, Mode=OneWay}"
FontStyle="{x:Bind Model.FirstNameError, Converter={StaticResource ErrorFontStyleConverter}, Mode=OneWay}"
FontSize="{x:Bind Model.FirstNameError, Converter={StaticResource ErrorFontSizeConverter}, Mode=OneWay}"
<Run Text="First Name" TextDecorations="{x:Bind Model.FirstNameError, Converter={StaticResource TextUnderlineConverter},Mode=OneWay}" />
</TextBlock>
Converter code:i have created multiple converters like below for ErrorColorConverter,ErrorFontSizeConverter and TextUnderlineConverter
public class ErrorFontStyleConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if ((bool)value)
return FontStyle.Italic;
else
return FontStyle.Normal;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
It works exactly the way i need, but i need some suggestions on if this can be done in better way?, do we have any ways to simplify this
Upvotes: 0
Views: 52
Reputation: 1882
You can use ConverterParameter
and receive them all from a single converter
<TextBlock Foreground="{x:Bind FirstNameError,Mode=OneWay,Converter={StaticResource ErrorToFont},ConverterParameter=foreground}"
FontStyle="{x:Bind FirstNameError,Mode=OneWay,Converter={StaticResource ErrorToFont},ConverterParameter=fontstyle}"
FontWeight="{x:Bind FirstNameError,Mode=OneWay,Converter={StaticResource ErrorToFont},ConverterParameter=fontweight}">
//Converter
public class ErrorFontConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (parameter.ToString() == "fontstyle")
return (bool)value ? Windows.UI.Text.FontStyle.Italic : Windows.UI.Text.FontStyle.Normal;
else if (parameter.ToString() == "foreground")
return (bool)value ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Blue);
else
return (bool)value ? FontWeights.Bold : FontWeights.Normal;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Upvotes: 2