2009-05-27 62 views
7

爲什麼下面的代碼得到運行時錯誤:如何獲取觸發器以基於DataContext屬性更改TextBlock的顏色?

Members of the Triggers collection must be of type EventTrigger

但EventTrigger元素沒有綁定屬性。

那麼如何根據DataContext屬性更改TextBlock的顏色?

XAML:

<Window x:Class="TestTrigger123345.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <StackPanel HorizontalAlignment="Left"> 
     <TextBlock Text="{Binding Status}"> 
      <TextBlock.Triggers> 
       <DataTrigger Binding="{Binding Status}" Value="off"> 
        <Setter Property="TextBlock.Background" Value="Red"/> 
       </DataTrigger> 
      </TextBlock.Triggers> 
     </TextBlock> 
    </StackPanel> 
</Window> 

代碼:

namespace TestTriggers 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
      DataContext = this; 
      Status = "off"; 
     } 

     public string Status { get; set; }  
    } 
} 

回答

13

那是因爲你只能設置事件直接觸發扳機物業..

使用風格以達到你想要什麼:

<Style x:Key="Triggers" TargetType="TextBlock"> 
    <Style.Triggers> 
     <DataTrigger Binding="{Binding Status}" Value="off"> 
      <Setter Property="TextBlock.Background" Value="Red"/> 
     </DataTrigger> 
    </Style.Triggers> 
</Style> 

下列對象有可能包含列出的觸發類型的觸發器的集合:

FrameworkElement  Style, ControlTemplate, DataTemplate 
----------------  ------------------------------------ 
EventTrigger   EventTrigger 
        Trigger or MultiTrigger 
        DataTrigger or MultiDataTrigger 
9

你可以做一個風格:

<TextBlock Text="{Binding Status}"> 
    <TextBlock.Style> 
     <Style TargetType="{x:Type TextBlock}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Status}" Value="off"> 
        <Setter Property="Background" Value="Red"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBlock.Style> 
</TextBlock> 
2

有一個錯字,你沒有關閉了Style.Triggers。我發現我需要使用屬性TextBlock.Background。謝謝,你讓我找到解決方案。

<TextBlock.Style> 
     <Style TargetType="{x:Type TextBlock}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Status}" Value="off"> 
        <Setter Property="TextBlock.Background" Value="Red"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBlock.Style> 
相關問題