动态路径上的wpf样式触发器

时间:2011-01-21 18:52:53

标签: wpf binding path styles

在下面的样式中,有没有办法使绑定路径通用,以便多个使用者可以使用此样式,每个使用者提供不同的绑定路径?

<Style x:Key="OptionalBackground"
       TargetType="{x:Type DataPresenter:CellValuePresenter}"
       BasedOn="{StaticResource OptionalFieldCellPresenter}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},
                                       Path=Record.DataItem.IsEditAllowed}"
                     Value="False">
            <Setter Property="Background" Value="{StaticResource ReadOnlyField}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

1 个答案:

答案 0 :(得分:0)

您可以从Style派生以创建如下所示的速记符号:

<local:BackgroundStyle
    x:Key="OptionalBackground"
    TargetType="{x:Type DataPresenter:CellValuePresenter}"
    BasedOn="{StaticResource OptionalFieldCellPresenter}"
    Path="Record.DataItem.IsEditAllowed"
    Value="{StaticResource ReadOnlyField}"/>

此实例的实现可能是:

public class BackgroundStyle : Style, ISupportInitialize
{
    public string Path { get; set; }
    public object Value { get; set; }

    public void BeginInit() { }

    public void EndInit()
    {
        var trigger = new DataTrigger
        {
            Binding = new Binding
            {
                Path = new PropertyPath(Path),
                RelativeSource = new RelativeSource(RelativeSourceMode.Self)
            },
        };
        trigger.Setters.Add(new Setter(Control.BackgroundProperty, Value));
        Triggers.Add(trigger);
    }
}