Yohanes Nurcahyo
Yohanes Nurcahyo

Reputation: 621

Get value from DataContext to MarkupExtension in Style Setter

I have a WPF MarkupExtension which is used to modify the ListBoxItem property for example Background. This Background new value is based on ListBoxItem.DataContext and MarkupExtension property, for example Color.

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

And my MarkupExtension is:

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. How can I get ListBoxItem.DataContext (it must be ColorfullItem instance) inside ProvideValue override method?
2. Is that possible?

Upvotes: 1

Views: 871

Answers (1)

mm8
mm8

Reputation: 169160

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

You can't really. You may access the root element but not the element to which the setter is actually applied:

Accessing "current class" from WPF custom MarkupExtension

  1. Is that possible?

No. You should probably consider implementing an attached behaviour or something else rather than a custom markup extension if you need this: https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF

Upvotes: 1

Related Questions