我需要在WPF中動態創建一個DataGrid。網格應使用動態生成的控件(組合框,文本框)填充行和列。我需要用三個coulmns和N行填充網格(行數基於XML文件中可用的XML節點)。我將WPF應用程序中的DocumentProperties.XML作爲內容。動態創建WPF組合框控件
<DocumentProperties>
<Properties>
<Property Name="DocumentName">
<Id>1</Id>
<Name>DocumentName</Name>
<Type>LogicalOperator</Type>
<Language>en-US</Language>
</Property>
<Property Name="TemplateUsed">
<Id>2</Id>
<Name>TemplateUsed</Name>
<Type>LogicalOperator</Type>
<Language>en-US</Language>
</Property>
....
</Properties>
<Operators>
<Category Type="LogicalOperator">
<Operator value="Equal"></Operator>
<Operator value="NotEqual"></Operator>
</Category>
<Category Type="TimeOperator">
<Operator value="Greater"></Operator>
<Operator value="Smaller"></Operator>
<Operator value="GreaterOrEqual"></Operator>
<Operator value="SmallerOrEqual"></Operator>
</Category>
</DocumentProperties>
在網格中,我需要在Colum1和Column2中創建一個ComboBox。 column1組合將加載XML中可用的Name屬性值。根據第一個組合框選擇的Type元素值,我需要使用Category節點中的值加載第二個組合框。網格中的3r列應該根據所選屬性的類型彈出文本框或Datepikcer。如果XML有6個屬性節點,那麼網格中的最大行數應爲< = 6。以上內容將用於選擇高級搜索的屬性。
我已經開始從後面的代碼創建網格。我已經試過了部分代碼如下:
documentPropertyCombo = new ComboBox[drivesCount];
operatorCombo = new ComboBox[drivesCount];
//Load the XML Document
XmlDataProvider xdp = new XmlDataProvider();
XmlDocument doc = new XmlDocument();
doc.Load(".\\Data\\DocumentProperties.xml");
xdp.Document = doc;
xdp.XPath = "DocumentProperties/Properties/Property";
xdp.Document = doc;
drivesGrid.DataContext = xdp;
var binding = new Binding("DocumentProperties/Properties/Property") { Source = xdp };
binding.Mode = BindingMode.OneTime;
// Adding ComboBoxes and TextBoxes to Grid.
for (int i = 0, j = 1; i < drivesCount; i++, j++)
{
//Initialize ComboBox to show Document Property.
//documentPropertyCombo[i] = new ComboBox();
documentPropertyCombo[i] = new ComboBox(); //CreateComboBox(new Thickness(30, 101, 0, 0), i + j, 1);
documentPropertyCombo[i].Width = 101;
documentPropertyCombo[i].Height = 30;
documentPropertyCombo[i].Visibility = Visibility.Visible;
//BindingOperations.SetBinding(myText, TextBlock.TextProperty, myBinding);
documentPropertyCombo[i].IsReadOnly = true;
documentPropertyCombo[i].DisplayMemberPath = "@Name";
BindingOperations.SetBinding(documentPropertyCombo[i], ComboBox.TextProperty, binding);
Grid.SetRow(documentPropertyCombo[i], i + j);
Grid.SetColumn(documentPropertyCombo[i], 1);
drivesGrid.Children.Add(documentPropertyCombo[i]);
...
}
LayoutRoot.Children.Add(drivesGrid);
控件是動態創建的,但該數據未綁定到ComboBox。我是否錯過了上面的代碼中的任何內容?我假設我可能需要動態地爲ComboxBox添加一個DataTemplate。任何人都可以驗證上述代碼嗎?另外我需要知道如何在Column1中爲動態創建的comboxBox添加事件,並根據Combo1中的選擇更新Column2中的ComboxBoxes的內容?
您能否提供WPF DataGrid的完整命名空間?它是WPFToolKit的一部分/默認情況下是否可用?有幾行示例代碼將幫助我重新執行我的任務。任何鏈接到教程也歡迎。 – saravana
http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx –
有一個內置的DataGrid,它附帶.Net 4.0 for WPF,但如果您使用的是早於版本的.Net框架需要得到你自己的。 – Rachel