You can use Converter for this. Simply Create class with IValueConverter. After in dataBinding use this converter
For example your XAML
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lib="clr-namespace:WpfApplication4"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<lib:TextBlockDataConveter x:Key="DataConverter"/>
<lib:TextBlockForegroundConverter x:Key="ColorConverter"/>
</Window.Resources>
<Grid>
<TextBlock Text="{Binding Path=message, Converter ={StaticResource DataConverter}}" Foreground="{Binding message, Converter={StaticResource ColorConverter}}"/>
</Grid>
and your converters:
public class TextBlockDataConveter:IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return "Error Message";
}
else
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
class TextBlockForegroundConverter:IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
SolidColorBrush brush = new SolidColorBrush();
brush.Color = Colors.Red;
return brush;
}
else
{
SolidColorBrush brush = new SolidColorBrush();
brush.Color = Colors.Black;
return brush;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
it works . Check it.