【问题标题】:Is there a way to add a resource to an UIElementCollection (like Grid.Children)?有没有办法将资源添加到 UIElementCollection(如 Grid.Children)?
【发布时间】:2022-01-18 13:54:15
【问题描述】:

在 XAML 文件中,我将图像定义为资源。当然,我可以将它分配为 ContenControl 的内容(如按钮)。 XAML 中是否有办法将此类资源添加到面板的子项(如网格)

<!--Creation of the Image as a resource (in this case loaded from assembly ressources)-->
<ResourceDictionary>
    <Image x:Key="CheckImage" x:Shared="False" Margin="0" Stretch="None" Source="/CheckStyleRes;component/CHECK.png" HorizontalAlignment="Center" VerticalAlignment="Center" IsHitTestVisible="True" SnapsToDevicePixels="True" UseLayoutRounding="True"/>
</ResourceDictionary>
...
<!--This is a workaround, putting the Image into an ContentControl and this into the Children-->
<Grid>
    <Grid.Children>
        <ContentControl x:Name="CheckMark" Content="{StaticResource CheckImage}"></ContentControl>
    </Grid.Children>
</Grid>
...
<!--But is there a syntax to add {StaticResource CheckImage} directly to Grid.Children-->
<Grid>
    <Grid.Children>
        <Image FromRessourceOrSomthingLikeThat= "{StaticResource CheckImage}">
    </Grid.Children>
</Grid>

我不想要 ImageSource 作为资源(然后我可以使用 Image 的 Source-Property 并在 Children 中创建图像)。我的资源应该是可以使用的图像。谢谢。

【问题讨论】:

    标签: c# wpf xaml resources


    【解决方案1】:

    你可以写

    <Grid>
        <StaticResourceExtension ResourceKey="CheckImage"/>
    </Grid>
    

    但您通常不会那样做。这不是将子元素添加到其父元素的典型方式。

    如以下评论中所述,您将无法在子元素上设置任何附加属性,例如 Grid.RowGrid.ColumnCanvas.LeftCanvas.TopDockPanel.Dock 等,这使得方法很没用。


    最好声明一个 BitmapImage 资源

    <BitmapImage x:Key="CheckImage" UriSource="/CheckStyleRes;component/CHECK.png"/>
    

    并添加这样的图像:

    <Grid>
        <Image Source="{StaticResource CheckImage}" Stretch="None"
               SnapsToDevicePixels="True" UseLayoutRounding="True"
               HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
    

    如果您不想在每次声明这样的图像时重复所有属性分配,请将它们移动到默认的图像样式中

    <Window.Resources>
        ...
        <Style TargetType="Image">
            <Setter Property="Stretch" Value="None"/>
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="UseLayoutRounding" Value="True"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
    </Window.Resources>
    

    【讨论】:

    • 要添加的一点是,使用&lt;StaticResourceExtension ResourceKey="CheckImage"/&gt; 方法,您不能添加任何附加属性,因为扩展名不是DependencyObject。因此,您甚至不能指定 Grid.Row,这在大多数情况下都会取消它的资格。
    • 感谢您的全面解释。在我的特殊情况下,我不需要设置那些附加属性(两个图像在同一位置,通过 VisualStateGroup 和 ObjectAnimationUsingKeyFrames 在“可见”和“折叠”之间切换)。但我将使用 Image.Source 的方式,这听起来对我来说更受欢迎。我真的很想知道,为什么将资源放入 ChildrensCollection 会有这么多问题。通过资源分配像 Image.Source 这样的属性非常简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2022-01-13
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多