我正在浏览stackoverflow以试图找出一种在ListView中设置GridViewColumns样式的方法。我偶然发现了这个:
WPF Text Formatting in GridViewColumn
最佳答案显示了如何设置一(1)个GridViewColumn的样式。我的问题是,有没有办法在Window.Resources中设置这些GridViewColumns的样式,所以我不必为每个GridViewColumn执行此操作?
答案 0 :(得分:2)
有几种可能性:
<!-- if style doesn't change -->
<GridViewColumn CellTemplate="{StaticResource yourCellTemplate}"/>
<!-- if you need to change it up based on criteria - template selector-->
<GridViewColumn CellTemplateSelector="{StaticResource YourTemplateSelector}"/>
<!-- same goes for headers -->
<GridViewColumn HeaderTemplate="{StaticResource yourheaderTempalte}"/>
..or HeaderContainerStyle, HeaderTemplateSelector
如果你想使用模板选择器:创建一个类,在资源字典中实例化它,并将它插入gridview列,这里有一个小样本
public class MyTemplateSelector : DataTemplateSelector
{
public DataTemplate SimpleTemplate { get; set; }
public DataTemplate ComplexTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
//if I have just text
return SimpleTemplate;
//if I have comments and other fancy stuff
return ComplexTemplate;
然后在你的ResourceDictionary
中
<DataTemplate x:Key="ComplexTemplate">
<Views:MyCustomControl DataContext="{Binding}"/>
</DataTemplate>
<Views:MyTemplateSelector
x:Key="TxtVsExpensiveCell_TemplateSelector"
SimpleTemplate ="{StaticResource SimpleTemplate}"
ComplexTemplate="{StaticResource ComplexTemplate}"/>
<!-- then you use it in your view like this -->
<GridViewColumn CellTemplateSelector="{StaticResource TxtVsExpensiveCell_TemplateSelector}"/>
如果你不想经历所有麻烦,以及如何调整预定义控件的样式,为什么不使用DataGrid呢?它有预定义的列,您可以在其中调整每个样式..
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn/>
<DataGridCheckBoxColumn/>
<DataGridHyperlinkColumn/>
<DataGridCheckBoxColumn/>
....there are several more column types!
</DataGrid.Columns>
</DataGrid>