【问题标题】:WPF DataTrigger that accepts parameter?接受参数的WPF DataTrigger?
【发布时间】:2014-11-05 18:28:14
【问题描述】:

我在我的 XAML 中定义了以下样式,以便仅在 DataContext 中的某些内容发生更改时启用按钮 (IsDirty = true):

   <!-- Style for Buttons to enable based on IsDirty value -->
    <Style x:Key="EnableWhenDirtyButtonStyle" TargetType="{x:Type Button}"
           BasedOn="{StaticResource ButtonStyle}">
        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <!-- Enable button when something has changed -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
                                           AncestorType={x:Type UserControl}}, Path=DataContext.IsDirty}" Value="True">
                <Setter Property="Button.IsEnabled" Value="true" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

只要在 UserControl 中只有一个 DataContext,它就可以工作。我现在的情况是我有 3 个不同的 DataView,所以我有 3 个不同的 IsDirty 值(即 CustomerTableIsDirty、OrderTableIsDirty、OrderDetailTableIsDirty)。在这种情况下,我可以在 UserControl 中创建三个新的 *DisableWhenDirtyButtonStyle,例如:

        <Style x:Key="CustomerTableEnableWhenDirtyButtonStyle" 
               TargetType="{x:Type Button}" 
               BasedOn="{StaticResource ButtonStyle}">
            <Setter Property="Button.IsEnabled" Value="False" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=CustomerTableIsDirty}" Value="true">
                    <Setter Property="Button.IsEnabled" Value="True" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

有没有办法创建一个 DataTrigger 以便可以将绑定值作为参数传递给样式?

或者,有没有办法在通过“BasedOn”继承样式时向 MultiDataTrigger 添加条件,该样式已经定义了 MultiDataTrigger。例如:

<Style x:Key="CustomerTableEnableWhenDirtyButtonStyle" 
                   TargetType="{x:Type Button}" 
                   BasedOn="{StaticResource EnableWhenDirtyButtonStyle}">

     <!-- Add the following to existing MultiDataTrigger in EnableWhenDirtyButtonStyle -->
     <Condition Binding="{Binding Path=CustomerTableIsDirty}" Value="true" />

</Style>

我不能使用 MultiBinding,因为这种样式是基础项目的一部分,它被多个其他项目(作为 DLL)使用。此 DLL 的用户将无法更新样式以包含必要的绑定路径。

【问题讨论】:

  • 创建附加行为怎么样?类似于here 描述的内容。

标签: c# wpf xaml datatrigger multibinding


【解决方案1】:

不要使用 3 个不同的名称,只需使用一个名称 IsDirty。

【讨论】:

  • 因为所有这些都在一个 UserControl 上,所以 CustomerTableIsDirty、OrderTableIsDirty、OrderDetailTableIsDirty 的值在一个 ViewModel 中。将它们简单地命名为“IsDirty”不是一种选择。我没有在我的帖子中提到它,但每个表都有自己的保存按钮,我正在尝试仅启用特定按钮。
猜你喜欢
  • 2018-04-07
  • 2013-12-30
  • 1970-01-01
  • 2016-06-18
  • 2012-04-02
  • 2015-04-22
  • 2012-01-09
  • 2018-09-30
  • 2013-06-04
相关资源
最近更新 更多