开发者

Bind to Static Resource with a Converter

I have a DataGrid and two StaticResource.

I want to bind RowStyle of DataGrid to one of two StaticResources.

RowStyle="{StaticResource {Binding Status, Converter={StaticResource MyConverter}}}"

MyConverter returns StaticResource's Ke开发者_JS百科y.

But I get this error:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.


The Static Resource key is not a value that can be assigned Dynamically. The name of the key needs to inline in the Xaml.

The correct approach is this:-

RowStyle="{Binding Status, Converter={StaticResource MyConverter}}" 

Where the converter that is stored against the "MyConverter" key returns a Style object. Note you could add a property of type ResourceDictionary to you converter and place you styles in that dictionary for you converter to lookup.

In fact I have already written a converter capable of this here.


// Another version of writing such a converter

public abstract class BaseConverter : MarkupExtension
{
    protected IServiceProvider ServiceProvider { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
        return this;
    }    
}


public class StaticResourceConverter : BaseConverter, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new StaticResourceExtension(value).ProvideValue(ServiceProvider);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //TODO - implement this for a two-way binding
        throw new NotImplementedException(); 
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜