How to bind collection to WPF:DataGridComboBoxColu

2019-01-26 04:18发布

Admittedly I am new to WPF but I have looked and looked and can't find a solution to this problem.

I have a simple object like:

class Item
{
  ....

  public String Measure { get; set; }
  public String[] Measures {get; }
}

Which I am trying to bind to a DataGrid with two text columns and a combo box column. For the combo box column, property Measure is the current selection and Measures the possible values.

My XAML is:

<DataGrid Name="recipeGrid" AutoGenerateColumns="False" 
          CellEditEnding="recipeGrid_CellEditEnding" CanUserAddRows="False"
          CanUserDeleteRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Food" Width="Auto"
                            Binding="{Binding Food.Name}" />
        <DataGridTextColumn Header="Quantity" IsReadOnly="False"
                            Binding="{Binding Quantity}" />

        <DataGridComboBoxColumn Header="Measure" Width="Auto"
                                SelectedItemBinding="{Binding Path=Measure}"
                                ItemsSource="{Binding Path=Measures}" />

    </DataGrid.Columns>
</DataGrid>

The text column are displayed just fine but the combobox is not - the values are not displayed at all. The binding error is:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Measures; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=11497055); target property is 'ItemsSource' (type 'IEnumerable')

How do I fix this?

Thanks

3条回答
forever°为你锁心
2楼-- · 2019-01-26 04:34

If your measures are common for all objects, then you can make measures static

public String[] Measures { get; }

And your xaml will use it as it's shown below:

<DataGridComboBoxColumn
    Header="Role"
    SelectedValueBinding="{Binding Role}"
    ItemsSource="{Binding Source={x:Static local:ProjectsDataContext.Roles}}"
    DisplayMemberPath="Name"/>

Hopefully, it will help.

查看更多
Animai°情兽
3楼-- · 2019-01-26 04:37

This is hands down the best solution:

http://wpfthoughts.blogspot.com/2015/04/cannot-find-governing-frameworkelement.html

The idea here is that you declare a CollectionViewSource as a static resource and then declaratively bind it to ItemsSource of the DataGridComboBoxColumn.

Create and bind a static CollectionViewSource:

 <Page.Resources>
     <CollectionViewSource x:Key="Owners" Source="{Binding Owners}"/>
 </Page.Resources>

And then bind your target ItemsSource:

ItemsSource="{Binding Source={StaticResource Owners}}"
查看更多
登录 后发表回答