2009-11-30 73 views
3

我一直在使用帶有數據觸發器的值轉換器時遇到問題。在我的一些代碼中,似乎DataTriggerPath正被應用於根元素,而不是該樣式適用的元素。簡單的WPF IValueConverter和DataTrigger不能一起工作

我創建了一個簡單的測試用例,我不明白它的行爲。我期望Button變成紅色或藍色,這取決於哪個值被送入DataTrigger的轉換器,但是Button根本沒有受到影響!

<UserControl 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:SimpleWpfApplication" 
    x:Class="SimpleWpfApplication.SimpleUserControl" 
    ToolTip="UserControl ToolTip"> 
    <UserControl.Resources> 
     <local:SimpleConverter x:Key="SimpleConverter" /> 
    </UserControl.Resources> 
    <Button ToolTip="Button ToolTip"> 
     <Button.Style> 
      <Style TargetType="{x:Type Button}"> 
       <Style.Triggers> 
        <DataTrigger 
         Binding="{Binding Path=ToolTip, Converter={StaticResource SimpleConverter}}" 
         Value="Button ToolTip"> 
         <Setter Property="Background" Value="Red" /> 
        </DataTrigger> 
        <DataTrigger 
         Binding="{Binding Path=ToolTip, Converter={StaticResource SimpleConverter}}" 
         Value="UserControl ToolTip"> 
         <Setter Property="Background" Value="Blue" /> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </Button.Style> 
    </Button> 
</UserControl> 

和一個簡單的轉換器:

class SimpleConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new InvalidOperationException("SimpleConverter is a OneWay converter."); 
    } 
} 

爲什麼不Convert被稱爲?爲什麼Button變成紅色或藍色?

回答

8

發現在另一個StackOverflow的問題的答案:What’s wrong with my datatrigger binding?

答案是添加RelativeSource={RelativeSource Self}到綁定:

<DataTrigger Binding="{Binding Path=ToolTip, 
         RelativeSource={RelativeSource Self}, 
         Converter={StaticResource SimpleConverter}}" />