【问题标题】:How to use resources defined in <Styles.Resources> inside Resource Dictionary如何在资源字典中使用 <Styles.Resources> 中定义的资源
【发布时间】:2012-03-17 05:53:37
【问题描述】:

我有一个资源字典,它是在其上定义的数据网格样式和该数据网格样式中的样式。

<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 留在里面 &lt;Style.Resources&gt;CatalogDataGrid

如何在我的 XAML 上使用 RightAlignedDataGridCell 而不将其移动到资源字典根目录?

提前致谢。

【问题讨论】:

    标签: wpf xaml resourcedictionary


    【解决方案1】:

    您必须将资源字典包含在您正在使用的任何控件/窗口等的资源部分中才能找到它。您可以通过MergedDictionaries 进行此操作。

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

    【讨论】:

    • x:Key="RightAlignedDataGridCell"。我认为你需要删除它。
    • 不能这样做..因为该列将左对齐。
    • 啊啊。对不起。我没有正确阅读你的问题。重新开始:你为什么不希望它在资源字典根目录中?我认为没有合乎逻辑的理由。
    • 您的问题的答案是,如果您在元素的资源部分中定义资源,则只能在元素中使用它。如果您在样式中定义它,您可以在样式中使用它。如果你想在外面使用它,请在外面定义它。你想做的事情是不可能的,更重要的是没有任何目的。
    • 我有 3 个数据网格样式,每个数据网格有 3 个对齐的单元格样式(左、中、右)。每个单元格样式都有不同的颜色背景。我只想将这些样式封装到相关的数据网格中。因此,这些数据网格的单元格样式名称将相同。感谢@NVM 指出它。我想我把事情复杂化了。我最终在 datagrid 样式上使用样式的 Trigger 和 Tag 来实现我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多