从资源字典中选择图像源路径

Choose image Source path from resourcedictionary

我有一个复选框,我用自定义图像设置样式。 我需要在运行时根据主题选择图像。 我只想更改图像而不是所有模板。 这是我的复选框模板:

<Style TargetType="{x:Type CheckBox}" x:Key="FlatCheckbox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CheckBox}">
                    <StackPanel Orientation="Horizontal">
                        <Image x:Name="checkboxImage" Source="/checked.png" Width="32"/>
                        <ContentPresenter/>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter TargetName="checkboxImage" Property="Source" Value="/unchecked.png"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

所以我只想从 ResourceDictionary 中获取 checkboxImage 的源路径(我可以在运行时选择它。) 例如,如果我可以在 ResourceDictionary 中放置一个关键的 ImagePath 并使用类似这样的东西

<Image x:Name="checkboxImage" Source="{ImagePath}" Width="32"/>

如何实现?

您可以将 BitmapImage 声明为 XAML 资源并将其引用为 DynamicResource,例如喜欢:

<Window.Resources>
    <BitmapImage x:Key="TestImage" UriSource="Image1.jpg"/>
    <Style x:Key="TestStyle" TargetType="ContentControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    <Image Source="{DynamicResource TestImage}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <ContentControl Style="{StaticResource TestStyle}"/>
</Grid>

然后你可以用一些其他的 BitmapImage 来替换资源,比如

public MainWindow()
{
    InitializeComponent();

    Resources["TestImage"] =
        new BitmapImage(new Uri("pack://application:,,,/Image2.jpg"));
}