2014-07-18 186 views
0

我創建了一個簡單的應用程序,使用xaml和C#將邊框顏色綁定到布爾方法IsToday後面的代碼。但不知何故,它不工作。WPF xaml DataTrigger綁定不起作用

有人可以幫忙嗎?我試過INotifyPropertyChanged,但它不起作用。感謝有人能幫忙,謝謝!

後面的代碼:

namespace WpfApplication3 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      IsToday = true; 
      InitializeComponent(); 
     } 

     public bool IsToday { get; set; } 
    } 
} 

XAML

<Window x:Class="WpfApplication3.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <ResourceDictionary Source="Dictionary1.xaml"> 
     </ResourceDictionary> 
    </Window.Resources> 
     <Grid> 
     <Border Style="{StaticResource Highlight}"> 
     </Border> 
    </Grid> 
</Window> 

XAML字典

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
     <Style TargetType="Border" x:Key="Highlight"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding IsToday}" Value="True"> 
        <Setter Property="Background" Value="Red"/> 
       </DataTrigger> 
       <DataTrigger Binding="{Binding IsToday}" Value="False"> 
        <Setter Property="Background" Value="Blue"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ResourceDictionary> 

回答

0

您可以從xaml設置上下文。

<Window x:Class="WpfApplication3.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525" 
     DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    <!-- your code --> 
</Window> 
+0

非常感謝!它現在有效 – user3854148

2

你必須設置DataContext爲您Window

public MainWindow() { 
     InitializeComponent(); 
     DataContext = this; 
     IsToday = true; 
} 

當然這隻適用於最初,之後對IsToday所做的每一項更改都不起作用。如您所知,我們必須執行INotifyPropertyChanged

+0

非常感謝! – user3854148