I have a Collection of Values in an Array of Strings, or in a List or whatever, and what i want is to set this Collection of values as the Collection of items into all the ComboBoxes in a column as DataGridComboBoxColumn in WPF.
I think i don't have other way to access this Collection of Values and bind it equally to all the ComboBoxes (in XAML) beside the DataContext. But can i access the DataContext of a DataGrid from a DatGridComboBoxColumn (in XAML)? Can i do it? How?
How i specify (in XAML) in DatagridComboBoxColumn to put this Collection of Items equally in all ComboBoxes? How i can achieve this?
Here is my XAML:
(...)xmlns:local="clr-namespace:WpfApp"(...)
<Grid Name="grid1">
<DataGrid Name="dataGrid" AutoGenerateColumns="True">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Options" Width="100"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
And here is my Code Behind:
public class TestClass
{
private static string[] stringArray = { "Option One", "Option Two", "Option Three" };
public static string[] StringArray
{
get
{
return stringArray;
}
}
}
There's no straightforward way to access the
DataContext
of theDataGrid
from the column definition, because it isn't part of the visual or logical tree, so it doesn't inherit the DataContext. I recently blogged about a solution to that issue. Basically you need to do something like that:BindingProxy
is a simple class that derives fromFreezable
and exposes aData
dependency property.In a binding where you only specify the
Path
the binding mechanism will implicitly use theDataContext
as the source. You only need to explicitly specify a source to avoid this (since you do not want the current row as your source).In one of my test applications i have a class
Employee
which has a few properties includingOccupation
, to use this with a ComboBox-column you need a list of occupations, where and how you define that list is up to you, one way to do is in the resources of the window or DataGrid:where
col
is the namespace:clr-namespace:System.Collections;assembly=mscorlib
To use this now i can specify the following in the
DataGrid.Columns
:This will allow me to assign one of the three "occupations" from my array as the
Occupation
of the employee in question.Another way to set up your source list is as a static property of some class that way you should be able to use: