How to bind the same collection of values into all ComboBoxes in a DataGridComboBox?

喜你入骨 提交于 2019-12-04 18:17:54

But can i access the DataContext of a DataGrid from a DatGridComboBox Column (in XAML)? Can i do it? How?

There's no straightforward way to access the DataContext of the DataGrid 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:

<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 is a simple class that derives from Freezable and exposes a Data dependency property.

In a binding where you only specify the Path the binding mechanism will implicitly use the DataContext 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 including Occupation, 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:

    <col:ArrayList x:Key="Occupations">
        <sys:String>Programmer</sys:String>
        <sys:String>GUI Designer</sys:String>
        <sys:String>Coffee Getter</sys:String>
    </col:ArrayList>

where col is the namespace: clr-namespace:System.Collections;assembly=mscorlib

To use this now i can specify the following in the DataGrid.Columns:

<DataGridComboBoxColumn SelectedValueBinding="{Binding Occupation}"
                        ItemsSource="{Binding Source={StaticResource Occupations}}"/>

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:

<DataGridComboBoxColumn ... ItemsSource="{Binding Source={x:Static namespace:Class.Property}}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!