How to use resources defined in <Styles.Resources> inside Resource Dictionary

15,165

You will have to include the resourcedictionary in the resource section of whatever control/window etc you are using for it to be found. You can do this via MergedDictionaries.

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="myresourcedictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
Share:
15,165
Steven Suryana
Author by

Steven Suryana

A pragmatic software engineer.

Updated on June 14, 2022

Comments

  • Steven Suryana
    Steven Suryana almost 2 years

    I have a resource dictionary which is a datagrid style defined on it and a style inside that datagrid style.

    <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>
    

    Then in my XAML I tried to use RightAlignedDataGridCell so that my column be right aligned.

    <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>
    

    When I run my app I received resource not found exception. If I put that style on resource dictionary root. It could work. But I want RightAlignedDataGridCell stays inside <Style.Resources> of CatalogDataGrid.

    How to use that RightAlignedDataGridCell on my XAML without moving it to resource dictionary root?

    Thanks in advance.