WPF DataGrid ComboBox 绑定到 ViewModel 中的集合和选择

WPF DataGrid ComboBox binding to collection and selection in ViewModel

我有一个基本的 MVVM WPF 应用程序,它在 DataGrid 中显示了一堆与用户相关的信息。我有两个 类(我简化了 类 并且没有像我的实际应用程序那样实现 INotifyPropertyChanged

public class Address
{
    public String StreetName { get; set; }
}

public class Person
{
    public String Name { get; set; }
    public String Street { get; set; }
}

我的 ViewModel 包含两个 ObservableCollections.

ObservableCollection<Person>
ObservableCollection<Address>

我将 ViewModel 绑定到 Window,它显示人员集合就好了。但现在我想要,地址作为 ComboBox 这样用户只能从上面的地址集合中获取 select 值。类似于查找 table.

这是我的 XAML 代码。我成功了,那是显示地址集合,但它不会显示我作为初始记录的人员集合的实际记录。

            <DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
            <DataGridTextColumn Header="Street" Binding="{Binding Street}"></DataGridTextColumn>

            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox ItemsSource="{Binding DataContext.addresses, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" DisplayMemberPath="StreetName">
                        </ComboBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

SelectedItemSelectedValue 属性(取决于您实际绑定到的内容)设置为地址。因此,如果您要存储街道名称,那么您将拥有:

<DataTemplate>
    <ComboBox ItemsSource="..."
              DisplayMemberPath="StreetName"
              SelectedValuePath="StreetName"
              SelectedValue="{Binding Street}"/>
</DataTemplate>