WPF Adding a ComboBox to a DataGrid or List View Based on different DB Tables

后端 未结 1 1487
梦谈多话
梦谈多话 2021-01-25 14:29

I would like to add a ComboBox to a DataGrid or ListView but the Combobox\'s underlying ViewSource would be filtered by data

相关标签:
1条回答
  • 2021-01-25 14:45

    I would do something like this

    View:

    <DataGrid x:Name="myGrid" ItemsSource="{Binding Companies}">
         <DataGrid.Columns>
             <DataGridTextColumn Binding="{Binding CompanyName}"/>
         </DataGrid.Columns>
         <ie:Interaction.Triggers>
            <ie:EventTrigger EventName="SelectionChanged">
                <ie:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"  CommandParameter="{Binding ElementName=myGrid, Path=SelectedItem}"/>
            </ie:EventTrigger>
        </ie:Interaction.Triggers>
    </DataGrid>
    <ComboBox ItemsSource="{Binding SelectedCompanyPhoneNumbers}"/>
    

    ViewModel:

    public class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            SelectedItemChangedCommand = new DelegateCommand<object>((selectedItem) => 
            {
                var selected = selectedItem as Company;
    
                SelectedCompanyPhoneNumbers = selected.CompanyPhoneNumbers;
            });
        }
    
        public view LoadCompanies()
        {
            // Load the companies information from different tables ...
        }
    
        public List<Company> Companies { get; set; }
    
        public DelegateCommand<object> SelectedItemChangedCommand { get; set; }
    
        public List<string> SelectedCompanyPhoneNumbers { get; set; }
    }
    

    Model:

    public class Company
    {
        public string CompanyName { get; set; }
    
        public List<string> CompanyPhoneNumbers { get; set; }
    }
    

    I used Prism framework in this example. The i and ie are shortcuts to namespaces:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactions"
    xmlns:ie="http://schemas.microsoft.com/expression/2010/interactivity"
    

    What happens here is that the viewModel holds a list of the selected company phone numbers. Whenever the company gets changed (a different row in the grid get's selected in this example) the selected company's phone numbers is changed accordingly.

    Here are some good links on MVVM:

    http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

    http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute

    http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

    Good luck

    0 讨论(0)
提交回复
热议问题