从 DataContext 获取值到样式中的 MarkupExtension Setter

Get value from DataContext to MarkupExtension in Style Setter

我有一个 WPF MarkupExtension 用于修改 ListBoxItem 属性 例如背景。此背景新值基于 ListBoxItem.DataContext 和 MarkupExtension 属性,例如颜色。

<ListBox ItemsSource="{Binding ColorfullItems}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Background" Value="{Helpers:MyMarkupExtension Color=Blue}" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

我的 MarkupExtension 是:

public class MyMarkupExtension : MarkupExtension
{
    public string Color { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        IProvideValueTarget provideValueTarget = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

        // The following target is a Setter instance, 
        // which doesn't have ListBoxItem.DataContext property.
        var target = provideValueTarget.TargetObject;

        // I put break point here.
        // **How can I get ListBoxItem.DataContext instance here?**
    }
}

1.如何在 ProvideValue 覆盖方法中获取 ListBoxItem.DataContext(必须是 ColorfullItem 实例)?
2. 可以吗?

  1. How can I get ListBoxItem.DataContext (it must be ColorfullItem instance) inside ProvideValue override method?

你真的不能。您可以访问根元素,但不能访问 setter 实际应用到的元素:

Accessing "current class" from WPF custom MarkupExtension

  1. Is that possible?

没有。如果需要,您可能应该考虑实现附加行为或其他东西而不是自定义标记扩展:https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF