Bạn có thể sử dụng Trình chuyển đổi cho việc này. Đơn giản chỉ cần tạo lớp với IValueConverter. Sau khi ở databinding sử dụng chuyển đổi
này Ví dụ XAML của bạn
<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>
và bộ chuyển đổi của bạn:
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
}
nó hoạt động. Kiểm tra nó.
Trong ngữ cảnh của câu hỏi, bạn có thể muốn đặt chế độ hiển thị trong kiểu/trình kích hoạt và đặt văn bản và màu sắc ở dòng đầu tiên. Tuy nhiên câu trả lời này vẫn tốt vì nó minh họa cho sự bắt đầu của định dạng phức tạp hơn. – apc