开发者

MVVMLight Multiple Listbox Selection

开发者 https://www.devze.com 2023-01-09 00:57 出处:网络
I have an ItemsContol bound to a Country model - which look like this. Country --int Id --string Name --List Counties

I have an ItemsContol bound to a Country model - which look like this.


Country

--int Id

--string Name

--List Counties


In the DataTemplate of the ItemsControl there's a Listbox - which is bound to the Counties property.

So what I want is only one item in 开发者_StackOverflow中文版any of the listboxes be selected at any one time.

For example: I have an item selected in the first listbox and I click an item in the second listbox, then the first listbox shouldn't have any selected items.

Any ideas ??


Add a SelectedCounty property to your Country object. Then you can bind the SelectedItem on your ListBox to that property. Then in code manually set all others to null. Something like so

Country.OnPropertyChanged += (s,e) => 
    {
         if(e.PropertyName == "SelectedCounty")
         {
             foreach(Country country in MyCountries)
                 if(country != sender)
                     country.SelectedCounty = null;
         }
    }


Just for reference here's the solution I'm using - it resides in the CountryViewModel

    private CountyModel _selectedcounty;
    public CountyModel SelectedCounty
    {
        get { return _selectedcounty; }
        set 
        { 
            _selectedcounty = value; 
            RaisePropertyChanged("SelectedCounty");

            if (value != null)
            {
                if (CountySelectedEvent != null)
                    CountySelectedEvent(value, EventArgs.Empty);

                Messenger.Default.Send<CountyModel>(value, "SelectedCounty");
            }
        }
    }

    public CountryViewModel()
    {
        Counties = new ObservableCollection<CountyModel>();

        Messenger.Default.Register<CountyModel>(this, "SelectedCounty",
            msg =>
            {
                if(msg != this.SelectedCounty && msg != null)
                    this.SelectedCounty = null;
            });
    }

Hope it helps someone :)

0

精彩评论

暂无评论...
验证码 换一张
取 消