如何将触发器与SourceName和DataTrigger结合使用?

5
在我的WPF控件中,我有以下两个触发器:
<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 : 无法从“String”(类型为“String”)获取“IsMouseOver”(类型为“Boolean”)的值。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

相关问题请参考这里 - LPL
相关,但并不有用,因为它没有使用任何SourceName属性。 - ygoe
2个回答

3
我已经尝试了很多方法,但没有找到有效的解决方案。除非有人证明我错了,否则我必须认为触发器和数据触发器不能结合使用。
我的解决方案是:不要试图从同一个触发器(需要不同的触发器类型)中访问本地属性和父元素属性,而是在子元素类中添加另一个DependencyProperty,并将其值绑定到父元素的属性。因此,子元素不需要查找父元素的值-它始终具有该值的当前副本。由于复制该值是在另一个位置完成的,因此保持触发器简洁小巧。 :-)
因此,这就是我的新增XAML代码的样子。以下是子项样式中的新setter:
<!-- 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>

依赖属性和数据绑定非常棒,但只有在它能正常工作时才是如此。但在此之前,它可能会非常糟糕。


1

我知道这是一个较旧的项目,但我想今天添加一些东西:即使您不能组合触发器和数据触发器,您也可以轻松将触发器升级为引用Self的数据触发器,如下所示:

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

这将使您能够将包含触发器的控件的条件与其他控件的条件组合,无需依赖属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接