Pergunta

I have and DataGridComboBoxColumn in the DataGrid a WPF window. I am assigning DataContext to Window as below:

cls = new MyClass
            {
                selValue = 2,
                DataGrid = dtGrid,
                ComboGrid = dtCombo
            };


            this.DataContext = cls;

Following is the XAML for DataGridComboBoxColumn:

    <DataGridComboBoxColumn Header="Item Name" SelectedValueBinding="{Binding Path=Item_Id}" SelectedValuePath="ItemId" DisplayMemberPath="ItemName">
            <DataGridComboBoxColumn.ElementStyle>
                <Style TargetType="ComboBox">
<!-- modified this code as per suggestion ///-->
                    <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.ComboGrid }" />
                </Style>
            </DataGridComboBoxColumn.ElementStyle>
            <DataGridComboBoxColumn.EditingElementStyle>
                <Style TargetType="ComboBox">
                    <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.ComboGrid }" />
                </Style>

            </DataGridComboBoxColu

mn.EditingElementStyle>

Still Combobox in grid showing blank. No data is being listed in Combobox. Then, I wrote following code in Windows codebehind, it start working.

((DataGridComboBoxColumn)this.testGrid.Columns[1]).ItemsSource = cls.ComboGrid.DefaultView;

Is there anyway to handle this case in XMAL itself using MVVM? I am reluctant to use this apporache.

Foi útil?

Solução

If the itemsSource is not within the datagrids itemssource you will have to find ancestor:

    <DataGridComboBoxColumn itemsSource="{binding RelativeSource={RelativeSource ancestortype=Page}, path=DataContext.YourComboboxItemsSource}" />

Assuming your datagrid is on a page, you can change the ancestortype to anything. You can use relativeSource on anything though. The reason for having to use this is that the itemssource you are trying to set is not part of the hierarchy so it can't find it. Hope this helps.

MVVM I would do something like:

 public list<string> ComboboxGridItemsSource { get; set; }
 //Then add some data in the property above.
 ComboboxGridItemsSource.add("Hello world1"); , ect...

And when this list gets altered/updated remember to raise the property using INotifyPropertyChanged.

 //After you implement INotifyPropertyChanged you can raise like this:
 RaiseProperty("ComboboxGridItemsSource");

Using MVVM you generally wouldn't manually set properties directly to the control but rather bind properties to that control in xaml.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top