How to bind an enumerator or variable to a DataGridComboBox in DataGrid in WPF?
I want to put the contents of an enumerator, or some array of strings or a specific DataTable as the items of a DatagridComboBox, so how i can bind the enumerator or the array of strings or a DataTable contents to a DataGridComboBox?
For example, i have a Datatable i will load to a DataGrid and will bind the records to customized columns, and depending on value of the cell (from the Da开发者_JAVA百科tatable) when the column (in the DataGrid) is a DataGridComboBox it will auto-select the corresponding item of the DataGridComboBox.
Binding columns as DataGridTextBox is easy, but columns as DataGridComboBox seems to be confusing.
My first problem is to put the items from (an Enumerator, or an array of strings, or a Datatable or whatever) to the DataGridComboBox, and the second problem is select the corresponding item when i load the DataTable which contains the records to the DataGrid.
Thanks in advance
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="300">
<StackPanel>
<toolkit:DataGrid Name="dataGrid" ItemsSource="{Binding Path=.}" AutoGenerateColumns="False">
<toolkit:DataGrid.Columns>
<toolkit:DataGridTemplateColumn>
<toolkit:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=StringArray}" Width="100"
SelectedValue="{Binding Path=SelectedString}" />
</DataTemplate>
</toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>
</StackPanel>
</Window>
In your code behind:
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ObservableCollection<TestClass> collection = new ObservableCollection<TestClass>();
collection.Add(new TestClass());
collection.Add(new TestClass());
collection.Add(new TestClass());
dataGrid.DataContext = collection;
}
}
public class TestClass
{
private static string[] stringArray = { "Option One", "Option Two", "Option Three" };
public string[] StringArray
{
get
{
return stringArray;
}
}
public string SelectedString
{
get;
set;
}
}
}
You need to set the datacontext of the window/control to some data behind and then you can use the properties of those objects to bind your controls.
I hope this helps
精彩评论