【问题标题】:Get value from DataContext to MarkupExtension in Style Setter在样式设置器中从 DataContext 获取值到 MarkupExtension
【发布时间】:2017-05-26 13:40:28
【问题描述】:

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

<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. 这可能吗?

【问题讨论】:

    标签: c# .net wpf xaml markup-extensions


    【解决方案1】:
    1. 如何在 ProvideValue 覆盖方法中获取 ListBoxItem.DataContext(它必须是 ColorfullItem 实例)?

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

    Accessing "current class" from WPF custom MarkupExtension

    1. 这可能吗?

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

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2020-08-11
      • 1970-01-01
      • 2013-06-13
      • 2011-11-21
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多