2010-04-26 5 views
14

문자열에 바인딩 된 WPF TextBlock이 있습니다. 해당 문자열이 비어 있으면 TextBlock에서 경고 메시지를 다른 색상으로 표시하려고합니다.조건부로 WPF TextBlock을 포맷합니까?

이것은 코드에서하기 쉽습니다. 우아한 WPF 순수 XAML 솔루션이 있다면 궁금합니다. 스타일 트리거를 조사했지만 문법이 자연스럽게 나에게 오지는 않습니다.

감사합니다.

BTW
<TextBlock Text="{Binding MyTextProperty}"> 
    <TextBlock.Style> 
     <Style TargetType="{x:Type TextBlock}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding MyTextProperty}" Value="{x:Null}"> 
        <Setter Property="Text" Value="Hey, the text should not be empty!"/> 
        <Setter Property="Foreground" Value="Red"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBlock.Style> 
</TextBlock> 

:이 완전히 메모리에서, 은 VS에서 그것을 확인하거나을 혼합하지 않았나요

답변

23

필요한 DataTrigger 물건의 일부로서 Daniel's (slightly short) answer에 몇 가지 세부 사항을 추가하면 (같은 {x:Null}가) 정말 사소한 아니다 , 거기에 오류가 있으면 변명하십시오. 그러나, 당신은 스스로 그것을 밖으로 정렬 할 수 있어야합니다. 아이디어는 무엇을 의미합니다. 행운을 빕니다!

+0

질문의 문맥에서 스타일/트리거에 가시성을 설정하고 텍스트와 색상을 첫 번째 줄에 설정하는 것이 좋습니다. 그러나이 대답은보다 복잡한 서식의 시작을 보여주기 때문에 여전히 좋습니다. – apc

9

이 경우 변환기를 사용할 수 있습니다. 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> 

하고 컨버터 예를 들어이 변환기

를 사용합니다. 확인해 봐.

+1

그런 간단한 작업을하기에는 너무 많은 코드라고 생각하지 않습니까?! – gehho

+1

네, 코드가 너무 많습니다. DataTriggers로 작업을 수행 할 수도 있습니다. 그러나이 솔루션은보다 유연합니다. – Polaris

+0

안녕하세요 Polaris, 감사합니다. 그러나 Xaml 전용 솔루션을 찾고있었습니다. –

관련 문제