【问题标题】:Creating an ItemsControl of Icon buttons with DynamicResource使用 DynamicResource 创建图标按钮的 ItemsControl
【发布时间】:2022-01-17 06:33:02
【问题描述】:

创建对动态资源做出反应的按钮(深色和浅色主题的样式)是这样完成的:

<Button>
  <Image Source="{DynamicResource IconId_12}" />
</Button>

当尝试对 ItemsControl 按钮的相同概念时遇到困难,每个按钮都有不同的图标,每个按钮都有一个键,指的是深色或浅色主题的图像源:

<ItemsControl ItemsSource="{Binding ButtonVMs}">
  <ItemsControl.Resources>
    <DataTemplate DataType="{x:Type ButtonVM}">
      <Button Command="{Binding ClickCommand}">
        <Image Source="{DynamicResource {Binding IconKey}}" />
      </Button>
    </DataTemplate>
  </ItemsControl.Resources>
</ItemsControl>

ButtonVM 如下所示:

public class ButtonVM {
  public Command ClickCommand { get; set; }
  public string IconKey { get; set; }
}

如何将资源键名绑定到动态绑定中?

我注意到您可以在代码中使用&lt;FrameworkElement&gt;.SetResourceReference(SourceProperty, "IconKey")。 (如this stackoverflow answer 中建议的那样)。但是这里的问题是VM不是FrameworkElement。

【问题讨论】:

    标签: c# xaml binding themes


    【解决方案1】:

    使用多值转换器,我能够访问 FrameworkElement(图像)并利用.SetResourceReferece() 来实现我需要的效果。

      public class ImageSourceKeyToDynamicResourceConverter : IMultiValueConverter
      {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
          var image = (Image)values[0];
          var key = (string)values[1];
          image.SetResourceReference(Image.SourceProperty, key);
          return frameworkElement.GetValue(Image.SourceProperty);
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
          throw new NotImplementedException();
        }
      }
    

    xaml 方面:

    <Image>
      <Image.Source>
        <MultiBinding Converter="{StaticResource KeyToDynamicResourceConverter}">
          <Binding RelativeSource="{RelativeSource Self}" />
          <Binding Path="IconKey" Mode="OneWay" />
        </MultiBinding>
      </Image.Source>
    </Image>
    

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 2012-06-15
      • 2018-11-12
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多