我在一个字符串数组中,或在列表或其他内容中有一个值集合,我想要的是将这个值集合作为项目集合设置为一个列中的所有组合框,作为WPF中的DataGridComboBoxColumn。
我认为我没有其他方法可以访问此Collection of Values并将其同等地绑定到DataContext旁边的所有ComboBoxes(在XAML中)。但是我可以从DatGridComboBoxColumn(在XAML中)访问DataGrid的DataContext吗?我可以做吗?怎么样?
我如何在DatagridComboBoxColumn中指定(在XAML中)将这个项目集合平等地放在所有ComboBox中?我怎么能做到这一点?
这是我的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>
这是我的代码背后:
public class TestClass
{
private static string[] stringArray = { "Option One", "Option Two", "Option Three" };
public static string[] StringArray
{
get
{
return stringArray;
}
}
}
答案 0 :(得分:3)
但是我可以从DatGridComboBox列(在XAML中)访问DataGrid的DataContext吗?我可以做吗?怎么样?
从列定义访问DataContext
的{{1}}没有直接的方法,因为它不是可视树或逻辑树的一部分,因此它不会继承DataContext。我最近在博客上发表了关于a solution to that issue的文章。基本上你需要做那样的事情:
DataGrid
<DataGrid Name="dataGrid" AutoGenerateColumns="True">
<DataGrid.Resources>
<!-- Proxy for the current DataContext -->
<local:BindingProxy x:Key="proxy" Data="{Binding"} />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Options" Width="100"
ItemsSource="{Binding Source="{StaticResource proxy}", Path=Data}"/>
</DataGrid.Columns>
</DataGrid>
是一个派生自BindingProxy
的简单类,并公开Freezable
依赖项属性。
答案 1 :(得分:1)
在只指定Path
的绑定中,绑定机制将隐式使用DataContext
作为源。您只需要明确指定一个源来避免这种情况(因为您不希望当前行作为源)。
在我的一个测试应用程序中,我有一个类Employee
,它有一些属性,包括Occupation
,要将它与ComboBox列一起使用,您需要一个职业列表,您在何处以及如何定义该列表取决于您,一种方法是在窗口或DataGrid的资源中使用:
<col:ArrayList x:Key="Occupations">
<sys:String>Programmer</sys:String>
<sys:String>GUI Designer</sys:String>
<sys:String>Coffee Getter</sys:String>
</col:ArrayList>
其中col
是命名空间:clr-namespace:System.Collections;assembly=mscorlib
现在使用此功能,我可以在DataGrid.Columns
中指定以下内容:
<DataGridComboBoxColumn SelectedValueBinding="{Binding Occupation}"
ItemsSource="{Binding Source={StaticResource Occupations}}"/>
这样我就可以将我的数组中的三个“职业”中的一个指定为相关员工的Occupation
。
设置源列表的另一种方法是使用某种类的静态属性:
<DataGridComboBoxColumn ... ItemsSource="{Binding Source={x:Static namespace:Class.Property}}"/>