问题描述
我的应用程序中有几个DataGrid,它们每个都有相同的模板。例如,以下是每个DataGrid的定义方式:
I've several DataGrid in my application and they each have the same "template". For example, here's how each DataGrid is defined:
<DataGrid Style="{StaticResource MainGridStyle}">
<DataGrid.Columns>
<DataGridTemplateColumn CanUserResize="False"
CanUserSort="False"
CanUserReorder="False"
CellStyle="{StaticResource RightCellStyle}">
...
如何在外部将 DataGridTemplateColumn定义为模板资源文件,因此我只需要写类似
How could I define the "DataGridTemplateColumn" as a Template in an external resource file, so I would simply have to write something like
<DataGridTemplateColumn Style={StaticResource MyFirstColumn}/>
在 MainGridStyle中,我定义了 CanUserAddRows等属性,...
In the "MainGridStyle" I define properties such "CanUserAddRows", ...
提前向您寻求帮助。
Fred
Thx in advance for your help.
Fred
推荐答案
由于 DataGridTemplateColumn
没有 Style
属性,因此您可以做的一件事就是创建一个附加属性。
Since DataGridTemplateColumn
does not have a Style
property, one thing you can do is create an attached property.
以下是一个示例:
[注意:,您可能需要将以下代码更改为适合您的项目。]
[NOTE: You may need to change the following code to suit you project.]
具有附加属性的类-
public class StyleExtensions
{
public static Style GetStyle(DependencyObject obj)
{
return (Style)obj.GetValue(StyleProperty);
}
public static void SetStyle(DependencyObject obj, Style value)
{
obj.SetValue(StyleProperty, value);
}
public static void StyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Style style = e.NewValue as Style;
if (style != null)
{
foreach (var s in style.Setters.OfType<Setter>())
{
d.SetValue(s.Property, s.Value);
}
}
}
// Using a DependencyProperty as the backing store for Style. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StyleProperty =
DependencyProperty.RegisterAttached("Style", typeof(Style), typeof(StyleExtensions), new UIPropertyMetadata(StyleChanged));
}
样式的定义
-
<Style x:Key="MyFirstColumn">
<Setter Property="DataGridColumn.CanUserResize"
Value="False" />
<Setter Property="DataGridColumn.CanUserSort"
Value="False" />
<Setter Property="DataGridColumn.CanUserReorder"
Value="False" />
<Setter Property="DataGridColumn.CellStyle"
Value="{StaticResource RightCellStyle}" />
</Style>
使用-
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn local:StyleExtensions.Style="{StaticResource MyFirstColumn}"></DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
这篇关于DataGrid和DataGridTemplateColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!