我正在尝试根据数据类型更改数据绑定DataGrid的水平列对齐方式(例如Int32,float,..)。
在网上搜索了我已经了解的一个简单的例子,通过xaml的DataTriggers应该是正确的选择。是对的吗?如果是这样,我将如何实现触发器?
我是WPF的新手,过去一直在使用WindowsForms。根据数据类型更改列方向并不困难?任何帮助表示赞赏!
答案 0 :(得分:1)
这可能有所帮助 - Different views / data template based on member variable
另一个选择是使用DataTemplate选择器。只需查看本教程:http://tech.pro/tutorial/807/wpf-tutorial-how-to-use-a-datatemplateselector
答案 1 :(得分:1)
您可以处理AutoGeneratingColumn事件。
在你的xaml中添加:
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True"
AutoGeneratingColumn="DataGrid_OnAutoGeneratingColumn"></DataGrid>
在代码隐藏中:
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof (Int32))
{
if (e.Column != null)
{
var dgct = new DataGridTemplateColumn();
var cName = e.Column.Header as string;
var b = new Binding(cName);
var sfactory = new FrameworkElementFactory(typeof(TextBlock));
sfactory.SetValue(TextBlock.TextProperty, b);
sfactory.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
var cellTemplate = new DataTemplate();
cellTemplate.VisualTree = sfactory;
dgct.CellTemplate = cellTemplate;
dgct.Header = cName;
dgct.SortMemberPath = cName;
e.Column = dgct;
}
}
... *and so on for all your data types*
}
您可以查看以下链接:
http://msdn.microsoft.com/en-us/library/cc903950(v=vs.95).aspx http://mareinsula.wordpress.com/2011/06/06/tips-on-wpf-autogeneratinged-datagrid/
答案 2 :(得分:0)
好的,我已经从现在的代码中解决了这个问题。也许有人可以给我一个暗示如何使用XAML更优雅地解决这个问题?我一直在网上搜索几个小时,找到一个对于刚接触WPF并且没有找到任何能够成功实现的东西的例子。
好的,这是代码:将DataTable作为DataSource添加以下内容:
foreach (DataColumn cc in table.Columns)
{
Type type = cc.DataType;
Style alignStyle = new Style(typeof(Microsoft.Windows.Controls.DataGridCell));
alignStyle.Setters.Add(new Setter(Microsoft.Windows.Controls.DataGridCell.VerticalAlignmentProperty, VerticalAlignment.Center));
var column = new Microsoft.Windows.Controls.DataGridTextColumn
{
Header = cc.ColumnName,
Binding = new Binding(cc.ColumnName)
};
if(type.Name=="Int32"){
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
column.Foreground = Brushes.Red;
column.CellStyle = alignStyle;
}
else if (type.Name == "DateTime")
{
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center));
column.Foreground = Brushes.Green;
column.Binding.StringFormat = "{0:dd.MM.yyyy}";
column.CellStyle = alignStyle;
}
else if (type.Name == "String")
{
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Left));
column.Foreground = Brushes.Blue;
column.CellStyle = alignStyle;
}
else if (type.Name == "Double")
{
alignStyle.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
column.Foreground = Brushes.Brown;
column.Binding.StringFormat = "{0:F3}";
column.CellStyle = alignStyle;
}
grids.Columns.Add(column);
}