如何使用DynamicResourceExtension将VM属性与资源密钥绑定?

时间:2019-06-02 14:54:35

标签: c# wpf xaml mvvm

我有按钮的图标资源,图标已转换为XAML资源格式。我需要将ViewModel的“ Icon Brush”属性绑定到DynamicResourceExtension键。

<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>
      <!-- This binding doesn't work, how can I solve the problem? -->
      <DynamicResource ResourceKey="{Binding IconBrush.ResourceKey, Mode=TwoWay}"/>
   </Button.Content>
</Button>

ViewModel的属性:

public DynamicResourceExtension IconBrush
{
  get { return _iconBrush; }
  set
  {
    SetProperty(ref _iconBrush, value, () => IconBrush);
  } 
}

属性初始化

IconResources resources = new IconResources();
IconBrush = resources.DrawIcon();

我用来控制资源的方法。我正在寻找更好的解决方案,因为我必须使用迭代器,所以这段代码也不完美。

 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;
 }

0 个答案:

没有答案