如何使用资源字典中的内定义的资源

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

问题描述:

我有一个资源字典,它是一个datagrid风格定义在它和datagrid风格内的风格。如何使用资源字典中的<Styles.Resources>内定义的资源

<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停留在 <Style.Resources>CatalogDataGrid

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

在此先感谢。

您将不得不将资源词典包含在您正在使用的任何控件/窗口的资源部分中。你可以通过MergedDictionaries来做到这一点。

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

我已经在我的xaml中包含了我的resourcedictionary。 – 2012-03-19 05:02:49

+0

x:Key =“RightAlignedDataGridCell”。你需要删除这个我认为。 – NVM 2012-03-19 07:48:00

+0

不能这样做,因为列将左对齐。 – 2012-03-20 14:21:00