由於DataGridTemplateColumn
沒有一個Style
財產,有一兩件事你可以做的就是創建一個附加屬性
下面是一個例子:
[注:你可能需要更改以下代碼以適合您的項目。]
具有附屬屬性的類 -
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
定義 -
<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>
嗯,這聽起來很瑣碎。如果我想在外部資源文件/字典中聲明這個「模板」?順便說一下,我的VisualStudio抱怨DataGridTemplateColumn中沒有Template屬性! – Fred 2010-11-23 08:55:06