Imad Nabil Alnatsheh
Imad Nabil Alnatsheh

Reputation: 400

Binding to member of Listbox item

I don't know if I would be informative enough, but I'm having a problem. I bound an ObservableCollection to a normal Listbox, everything is working fine, but ImageInfo has a member (Source) which contains the place where the image is, and I need the Source member of the current selected item in the Listbox. However, I don't seem to have a clue where to start.

Upvotes: 0

Views: 98

Answers (2)

djangojazz
djangojazz

Reputation: 13270

Are you binding in normal mode to a property like: EG: < combobox itemssource={Binding Listing}/>? If so you really just need to have a public property exposed for the 'selecteditem' if memory serves. The real power in Observable Collection from my understanding of WPF is how things can change in real time and you can notice those changes when implementing INotifyPropertyChanged or INotifyCollectionChanged.

<combobox x:Name="mycombo" itemssource="{Binding itemsource}" 
          selecteditem="{Binding SelectedItem}" />

ViewModel property:

public string SelectedItem { get; set; }

However if you want your property to be noticed when it changes you need to implement INotifyPropertyChanged. Typically then in studios I have worked in they set a private variable at the top of the class and then use it in the get set and then use the public property in bindings.

public class example : INotifyPropertyChanged
{
    private string _SelectedItem;


    public string SelectedItem 
    {
        get { return _SelectedItem; }
        set
        {
           _SelectedItem = value;

           RaisePropertyChanged("SelectedItem");
         }
    }

    public event PropertyChangedEventHandler PropertyChanged;

     protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new   System.ComponentModel.PropertyChangedEventArgs(propertyName));
    }

    public void DoSomething()
    {
         Messagebox.Show("I selected: " + SelectedItem);
    }
}

Upvotes: 1

Bianca Daniciuc
Bianca Daniciuc

Reputation: 930

Maybe you need in your xaml something like <Image Source="{Binding ElementName=myListbox, Path=SelectedItem.Source}"> . Other examples and explanations related to binding here https://stackoverflow.com/a/1069389/1606534

Upvotes: 1

Related Questions