2012-07-27 49 views
3

在我的WPF控件,我有以下兩個觸發器:如何將觸發器與SourceName和DataTrigger結合使用?

<Trigger 
    Property="Controls:TreeViewExItem.IsMouseOver" 
    Value="True" 
    SourceName="ElementGrid"> 

<DataTrigger 
    Binding="{Binding 
    RelativeSource={RelativeSource AncestorType={x:Type Controls:TreeViewEx}}, 
    Path=HoverHighlighting}" 
    Value="False"> 

兩個爲自己工作的罰款。但我需要這些的組合。我試過這個:

<MultiDataTrigger> 
    <MultiDataTrigger.Conditions> 
    <Condition 
     Binding="{Binding 
     RelativeSource={RelativeSource AncestorType={x:Type Controls:TreeViewEx}}, 
     Path=HoverHighlighting}" 
     Value="True"/> 
    <Condition 
     Binding="{Binding 
     (Controls:TreeViewExItem.IsMouseOver), 
     Source=ElementGrid}" 
     Value="True"/> 
    </MultiDataTrigger.Conditions> 

但它什麼也沒做。我在輸出窗口中看到這條消息:

System.Windows.Data Error: 17 : Cannot get 'IsMouseOver' value (type 'Boolean') from '' (type 'String'). BindingExpression:Path=(0); DataItem='String' (HashCode=1047858601); target element is 'TreeViewExItem' (Name=''); target property is 'NoTarget' (type 'Object') InvalidCastException:'System.InvalidCastException: Das Objekt des Typs "System.String" kann nicht in Typ "System.Windows.DependencyObject" umgewandelt werden.

這並沒有告訴我任何東西。它將如何工作?

更新:完整的項目代碼現在可在我的GitHub存儲庫中查看。我對MultiDataTrigger的猜測當前位於at

+0

相關問題[這裏](http://stackoverflow.com/q/602517/620360)。 – LPL 2012-07-27 11:31:50

+0

相關,但沒有幫助,因爲它不使用任何SourceName屬性。 – ygoe 2012-07-27 15:09:29

回答

1

我已經嘗試了很多東西,並沒有發現任何工作。直到有人證明我錯了,我必須假設Triggers和DataTriggers不能合併。

我的解決方案是另一種:不是試圖從同一觸發器(它需要不同的觸發器類型)訪問本地屬性和父元素屬性,而是將另一個DependencyProperty添加到我的子元素類並將其值綁定到父元素的屬性。因此,子元素不需要查找父元素值 - 它始終具有該值本身的當前副本。由於複製該值在另一個位置完成,因此它使觸發器保持良好和小巧。 :-)

所以這就是我添加的XAML代碼的樣子。下面是該子項的風格新二傳:

<!-- Pass on the TreeViewEx' HoverHighlighting value to each item 
    because we couldn't access it otherwise in the triggers --> 
<Setter 
    Property="HoverHighlighting" 
    Value="{Binding (Controls:TreeViewEx.HoverHighlighting), 
    RelativeSource={RelativeSource 
     AncestorType={x:Type Controls:TreeViewEx}}}" /> 

而且這是在觸發部分在所有其他觸發器已經:

<!-- Set the border and background when the mouse is located over 
    the item and HoverHighlighting is active --> 
<MultiTrigger> 
    <MultiTrigger.Conditions> 
    <Condition 
     Property="Controls:TreeViewExItem.HoverHighlighting" Value="True"/> 
    <Condition 
     Property="Controls:TreeViewExItem.IsMouseOver" Value="True" 
     SourceName="ElementGrid"/> 
    </MultiTrigger.Conditions> 

依賴屬性和數據綁定是很大的,一旦它作品。但在那之前,這可能是可怕的。

0

我知道這是一個較舊的項目,但我想添加一些東西,我今天發現:即使您不能組合觸發器和數據觸發器,您可以輕鬆地將觸發器升級到引用自我的DataTrigger,如所以:

<MultiDataTrigger.Conditions> 
    <Condition Binding="{Binding ElementName=TabsApp, Path=SelectedIndex}" value="0"/> 
    <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled}" Value="False"/> 
</MultiDataTrigger.Conditions> 

這將使你的條件組合關於含有約其他控件,無需依賴屬性條件觸發控制。