【问题标题】:Choose image Source path from resourcedictionary从资源字典中选择图像源路径
【发布时间】:2020-07-26 12:38:05
【问题描述】:

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

<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 的 Source 的路径(我可以在运行时选择它。) 例如,如果我可以在 ResourceDictionary 中放置一个关键 ImagePath 并使用类似这样的东西

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

如何做到这一点?

【问题讨论】:

    标签: wpf resourcedictionary


    【解决方案1】:

    您可以将 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"));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 2016-10-23
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多