Bind to a static resource using a converter

I have a DataGrid and two StaticResource .

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

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

MyConverter returns a StaticResource key.

But I get this error:

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

+4
source share
2 answers

The Static Resource key is not a value that can be assigned Dynamically . The key name must be embedded in Xaml.

The correct approach is as follows: -

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

If the converter, which is stored in the "MyConverter" key, returns a Style object. Please note that you can add a property of type ResourceDictionary to your converter and put styles into this dictionary for your converter to search for.

In fact, I already wrote a converter capable of this here .

+2
source
 // 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
source

Source: https://habr.com/ru/post/1334919/


All Articles