接受参数的WPF DataTrigger?

时间:2014-09-11 17:29:59

标签: c# wpf xaml datatrigger multibinding

我在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个不同的DataViews,所以我有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,以便绑定值可以作为参数传递给样式?

或者,有没有办法在通过已经定义了MultiDataTrigger的'BasedOn'继承样式时向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的用户将无法更新样式以包含必要的绑定路径。

1 个答案:

答案 0 :(得分:0)

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