이 경우 변환기를 사용할 수 있습니다. IValueConverter로 클래스를 생성하십시오.
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
}
작동 : 후 데이터 바인딩에 당신의 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>
하고 컨버터 예를 들어이 변환기
를 사용합니다. 확인해 봐.
질문의 문맥에서 스타일/트리거에 가시성을 설정하고 텍스트와 색상을 첫 번째 줄에 설정하는 것이 좋습니다. 그러나이 대답은보다 복잡한 서식의 시작을 보여주기 때문에 여전히 좋습니다. – apc