如何在资源字典中使用<Styles.Resources>定义的资源?

5
我有一个资源字典,其中包含一个数据网格样式和该数据网格样式内的样式。
<Style TargetType="{x:Type DataGrid}" x:Key="CatalogDataGrid">
    <Style.Resources>
        <Style TargetType="{x:Type DataGridCell}" x:Key="RightAlignedDataGridCell">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Border
                            Padding="5,0"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            SnapsToDevicePixels="True">
                            <ContentPresenter
                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                            VerticalAlignment="Center"
                            HorizontalAlignment="Right"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Style.Resources>
</Style>

然后在我的XAML中,我尝试使用RightAlignedDataGridCell来使我的列右对齐。

<DataGrid... Style="{StaticResource CatalogDataGrid}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}">
        </DataGridTextColumn>
        <DataGridTextColumn Header="Total" Binding="{Binding Total}"
                            CellStyle="{StaticResource RightAlignedDataGridCell}">
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

当我运行我的应用程序时,我收到了资源未找到异常。如果我将该样式放在资源词典根目录上,它可以工作。但是我想让RightAlignedDataGridCell保留在CatalogDataGrid<Style.Resources>中。
如何在不将其移动到资源字典根目录的情况下,在我的XAML中使用RightAlignedDataGridCell
提前感谢。
1个回答

2

如果想让资源字典被找到,您需要在使用它的控件/窗口等资源部分中包含它。您可以通过MergedDictionaries来完成这个过程。

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="myresourcedictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

x:Key="RightAlignedDataGridCell"。我认为你需要将其删除。 - NVM
无法这样做,因为该列将左对齐。 - Steven Suryana
啊啊,抱歉。我没有正确地阅读你的问题。重新开始:为什么你不想要它在ResourceDictionary根目录中?我看不出有任何逻辑上的理由。 - NVM
你的问题的答案是,如果你在一个元素的资源部分定义了一个资源,那么你只能在该元素内使用它。如果你在样式中定义它,你可以在样式中使用它。如果你想在外部使用它,请在外部定义它。你想做的事情是不可能的,更重要的是没有任何意义。 - NVM
我有3种数据网格样式,每个数据网格都有3种对齐的单元格样式(左、中、右)。每个单元格样式都有不同的背景颜色。我只想将这些样式封装到相关的数据网格中。这样,这些数据网格的单元格样式名称将是相同的。感谢@NVM指出。我想我把事情搞复杂了。最终,我使用样式的触发器和标签在数据网格样式上实现了我想要的效果。 - Steven Suryana

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