WPF MVVMLight: Update DataGrid based on SelectedItem of another DataGrid

大城市里の小女人 提交于 2019-12-01 14:20:30

The ItemsSource of a grid must be IEnumerable. So this:

ItemsSource="{Binding Main.SelectedAttribute}"

will not work because SelectedAttribute is an instance of a class, not some sort of list.

You are also binding something that presumably does implement IEnumerable (categories) to a DataTextColumn, which is also wrong; the binding of a grid column must be a scalar property.

EDIT: You're not going to be able to bind thee columns in a grid to three separate observable collections directly; you are going to need to make a new model class to hold the stuff you want to show up in the grid, like:

public class SomeGridItem
{
    public string Category {get; set;}
    public string SecondProp {get; set;}
    public string ThirdProp [get; set;}
}

Then add a new property on your view model -- this is what you will bind the grid to:

public ObservableCollection<SomeGridItem> Blahs {get; set;}

Then when the SelectedAttribute changes, you will need to populate Blahs. You could do this in the property setter for SelectedAttribute (probably easiest), or you could react to SelectedAttribute's PropertyChanged event. This is pseudocode, but it should give you an idea of what needs to be done.

Blah.Clear();

for (var i = 0; i < SelectedAttribute.Categories.Count; i++) {
   Blahs.Add(new SomeGridItem() {
        Category = SelectedAttribute.Categories[i],
        SecondProp = SelectedAttribute.SecondCollection[i],
        ThirdProp = SelectedAttribute.ThirdCollection[i]
    });
}

Then bind to your grid.

<DataGrid SelectionMode="Single" EnableColumnVirtualization="True" AutoGenerateColumns="false" ItemsSource="{Binding Main.Blahs}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="categories" Width="auto" Binding="{Binding Category}"  />                      
        <DataGridTextColumn Header="categories" Width="auto" Binding="{Binding SecondProp}"  />                      
        <DataGridTextColumn Header="categories" Width="auto" Binding="{Binding ThirdProp}"  />                      
    </DataGrid.Columns>
</DataGrid>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!