2012-03-17 44 views
2

我有一個資源字典,它是一個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而不將其移動到資源字典根目錄?

在此先感謝。

回答

1

您將不得不將資源詞典包含在您正在使用的任何控件/窗口的資源部分中。你可以通過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