2017-05-26 81 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

    我以爲我已經做到了。 :-) –