[英]WPF databound Datagrid change horizontal column orientation depending on data type
我試圖根據數據類型(例如Int32,float,..)更改數據綁定DataGrid的水平列對齊方式。
在網上搜索了我已經了解的一個簡單的例子,通過xaml的DataTriggers應該是正確的選擇。 那正確嗎? 如果是這樣,我將如何實現觸發器?
我是WPF的新手,過去一直在使用WindowsForms。 根據數據類型更改列方向並不困難? 任何幫助表示贊賞!
這可能有所幫助 - 基於成員變量的不同視圖/數據模板
另一種選擇是使用DataTemplate選擇器。 請查看本教程: http : //tech.pro/tutorial/807/wpf-tutorial-how-to-use-a-datatemplateselector
您可以處理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-數據網格/
好吧,我已經從現在的代碼中解決了這個問題。 也許有人可以給我一個暗示如何使用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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.