A
A
AlexSofar2019-06-02 09:38:12
WPF
AlexSofar, 2019-06-02 09:38:12

How to bind a VM property to a "ResourceKey" using the DynamicResource extension?

I have icon resources for buttons, icons are represented as XAML Resource. I need to bind the IconBrush property from the view model to the DynamicResource extension key.

<Button
     Grid.Row="2"
     Grid.Column="1"
     Width="48"
     BorderBrush="{x:Null}"
     Command="{Binding OpenDialogIcons}"
     CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}}"
     Style="{StaticResource BubleButton}">
     <Button.Content>
         <!-- Данная привязка не работает, как можно решить проблему? -->
         <DynamicResource ResourceKey="{Binding IconBrush.ResourceKey, Mode=TwoWay}"/>
     </Button.Content>
 </Button>

Property from view model:
public DynamicResourceExtension IconBrush
{
    get { return _iconBrush; }
    set
    {
        SetProperty(ref _iconBrush, value, () => IconBrush);
    }
}

Initialization property:
IconResources resources = new IconResources();
IconBrush = resources.DrawIcon();

In this method, I get icon resource management. This code is also imperfect, I'm looking for better solutions because I have to use an iterator.
public DynamicResourceExtension DrawIcon()
{
    ResourceDictionary resource = new ResourceDictionary();
    resource.Source = new Uri("../../Resources/Icons.xaml", UriKind.Relative);
    DynamicResourceExtension dynamicResource = new DynamicResourceExtension();

    foreach (var key in resource.Keys)
    {
        if ((string) key == "SettingIcon")
            dynamicResource.ResourceKey = key;
    }
    return dynamicResource;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question