如何在XAML中引用动态资源,而不是作为属性,而是作为元素?

3

我有一张图片需要在我的应用程序中多次使用。我想在资源字典中定义这个图像,然后让我的其他XAML文件引用这个定义。我可以做到这一点,但是我还没有弄清楚如何引用一个作为XAML元素而不是XAML属性定义的东西。

这是我的ResourceDictionary:

# resourceDictionary.xaml

<LinearGradientBrush x:Key="MyGradient" StartPoint="0,0.5" EndPoint="1,0.5">
    <GradientStop Color="#A5000000" Offset="0"/>
    <GradientStop Color="#00000000" Offset="1"/>
</LinearGradientBrush>

<Image x:Key="MyImage" Source="MyGlyph.png" Width="20" Height="20" />

在我的XAML中,我知道如何将渐变作为控件对象的属性进行引用。
<TextBlock Text="Sample Text" Background="{DynamicResource MessageGradient}"/>

但我想要弄清楚的是如何引用完整的控件对象Image。这个例子只是在按钮中创建了文本“{DynamicResource MyImage}”,而不是图片。

<!-- Want MyImage to be content of the button -->
<Button>
   {DynamicResource MyImage}
</Button>

有没有一种简单的方法来实现这个,还是我必须创建一个仅包含我的图像的控件模板,然后在我的xaml中使用一个使用控件模板的图像标签?

3个回答

5

如果你希望将图片作为按钮的内容,那么你应该可以将其绑定到 Content 属性:

<Button Content="{DynamicResource MyImage}" />

3
<!-- Want MyImage to be content of the button --> 
<Button> 
   <DynamicResource  ResourceKey="MyImage"/>
</Button> 

0
如果您正在尝试将图像作为任何控件的背景,请使用以下代码:
  <Button  Content="My Button">
        <Button.Background>
            <ImageBrush   ImageSource="MyGlyph.png"/>
        </Button.Background>
    </Button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接