views:

78

answers:

2

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 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 ??

A: 

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;
         }
    }
Stephan
I was just about to delete this post cause I sorted it out. That example you used would work, but it's not very elegant IMO. I create a CountryViewModel and had a SelectedCounty in there and when it changed I broadcast a Message and in each of the CountryViewModels I had a Registered for the notifications - and if it's not in the same ViewModel then I'll set it to null - easy peasy....I wish :) thanks for taking the time to reply anyway - appreciated.
IrishJoker
@IrishJoker: And that was awesome. You can make an answer as well.
Veer
@IrishJoker: If I understand it correctly, you're setting the SelectedCountry to null. If so, it'll again broadcast a message. So before broadcasting the change notification check if it's not null.
Veer
@Veer - Yeah I'm already doing that along with checking that the current SelectedCounty isn't the same as the one that sent it. I have it all working now in my test app nicely - now all I need to do is use it in my production app :) Fun times :P
IrishJoker
A: 

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 :)

IrishJoker