简体   繁体   中英

Filter a combobox in a datagrid based on another combobox column in the same row

i am new to wpf and i want to know how can i implement 2 comboboxes columns in a datagrid where the first combobox contains Countries ,and the other contains cities so while editing on datagrid cities colunmn combobox is filtered by the country selected in countries combo box using MVVM pattern

Thanks

Of course this is possible, the easiest way is to let your ViewModel do the filtering:

public class Data:ModelBase
{
    public ObservableCollection<string> Countries { get; set; }
    private List<City> _allCities = new List<City>();

    public IEnumerable<City> Cities
    {
        get
        {
            if (_selectedCountry == null)
                return _allCities;

            return _allCities.Where(c => c.Country == _selectedCountry);
        }

    }

    public Data()
    {
        Countries = new ObservableCollection<string>();
        //Fill _allCities and Countries here
    }

    private string _selectedCountry;
    public string SelectedCountry
    {
        get
        {
            return _selectedCountry;
        }
        set
        {
            if (_selectedCountry != value)
            {
                _selectedCountry = value;
                OnPropertyChanged("SelectedCountry");
                OnPropertyChanged("Cities");
            }
        }
    }
}

public class City
{
    public string Country { get; set; }
    public string Name { get; set; }
}

Now you bind your DataGrid to a collection of your Data-class. The ItemsSource of your Country-ComboBoy is bound to Countries, the one from your Cities-ComboBoy is bound to Cities and the SelectedItem of your Country-CB is bound to your SelectedCountry (Mode=TwoWay).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM