2017-10-15 201 views
1

我必須在DataGrid中顯示具有列樣式爲ComboBox或TextBlock的一組數據。 DataGrid綁定到一個DataTable。 DataTable中每列的數量和位置是在運行時定義的,所以我通過編程創建了DataGrid。 一切都很好,只要我使用DataGridTextColumn並保留默認樣式(TextBlock),而如果我嘗試將DataGridTextColumn更改爲TextBox樣式時出現類型錯誤。 有什麼關注的ComboBox沒有問題的,所以我貼以下只是我的代碼DataGridTextColumn部分(單DataGrid單元格):WPF Datagrid綁定到DataTable和TextBox樣式在代碼後面

C#

// Create the DataTable that will contain real-time data 
public DataTable CurrentTable { get; set; } 

// Binding string 
string stringA = "some_string_A"; 

// Create new binding 
Binding b = new Binding(stringA); 
b.Mode = BindingMode.TwoWay; 

// Create a new TextColumn 
DataGridTextColumn dgCol = new DataGridTextColumn(); 

//dgCol.ElementStyle = new Style(typeof(TextBox)); <- this row generates error 

// Set the column binding for the new TextColumn 
dgCol.Binding = b; 

// Add the TextColumn to the DataGrid 
datagrid.Columns.Add(dgCol); 

// Create a new row in the DataTable 
var colDataTable = CurrentTable.NewRow(); 

// Populate column "stringA" of the new row 
colDataTable[stringA]="some_string_B"; 

// Add the row to DataTable 
CurrentTable.Rows.Add(colDataTable); 

// Finally bind DataGrid to DataTable 
datagrid.ItemsSource = CurrentTable.AsDataView(); 

XAML

<DataGrid x:Name="datagrid" ItemsSource="{Binding CurrentTable}" CanUserAddRows="True" /> 

我試圖以很多方式將列樣式更改爲TetBox,可能我誤解了一些東西,有人能讓我知道嗎?

回答

0

你應該編輯 ElementStyle屬性爲您TextBox風格:

dgCol.EditingElementStyle = new Style(typeof(TextBox)); 

一個DataGridTextColumn有兩種風格。一個用於顯示,另一個用於編輯。

+0

完美!非常感謝你! – Boltzmann