2017-05-26 79 views
1

我有一个WPF MarkupExtension它用于修改ListBoxItem属性为例如Background。此背景新值基于ListBoxItem.DataContext和MarkupExtension属性,例如Color。从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.我怎样才能得到ListBoxItem.DataContext(必须是ColorfullItem实例)ProvideValue重写方法里面?
2.这可能吗?

回答

1
  1. 我怎样才能得到ListBoxItem.DataContext(必须是ColorfullItem实例)ProvideValue重写方法里面?

你不可能真的。你可以访问根元素,但不实际施加装定的元件:

Accessing "current class" from WPF custom MarkupExtension

  • 这可能吗?
  • 号你或许应该考虑实施附加的行为或别的东西,而不是一个自定义标记扩展,如果你需要这样的:https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF

    +0

    很清楚,我将尝试使用附加的行为。 –

    +1

    我以为我已经做到了。 :-) –