panjo
panjo

Reputation: 3515

Display ListBox SelectedItem

I've just read this question and I'm having problems with its implementation.

MainWindow has listbox with some data. On selected item inside that listbox I want to display in textblock at status bar on same window selected data is DataOne where DataOne represents Name property.

MainWindow.xaml

<ListBox Name="listBoxData"              
         ItemsSource="{Binding MyListBoxData}" SelectedItem="{Binding SelectedData}" />

Inside status bar element

<TextBlock Text="{Binding SelectedData.Name, StringFormat='Selected data is: {0}'}">  

MainWindowViewModel

public MyData SelectedData {get; set;}

p.s. just to clarify data is properly displayed inside listbox, DataContext is set inside ViewModel constructor.

Upvotes: 1

Views: 67

Answers (2)

Sheridan
Sheridan

Reputation: 69985

You should be able to bind directly to the selected item from the MyListBoxData collection like this:

<TextBlock Text="{Binding MyListBoxData/Name, StringFormat='Selected data is: {0}'}">

If it doesn't work at first, you might need to set the IsSynchronizedWithCurrentItem property on the ListBox to True:

<ListBox Name="listBoxData" IsSynchronizedWithCurrentItem="True"             
    ItemsSource="{Binding MyListBoxData}" />

Upvotes: 1

Peter Hansen
Peter Hansen

Reputation: 8907

It looks like you're not implementing the INotifyPropertyChanged interface in the viewmodel?

You have to do that in order for the binding-system to know when to update the value in the TextBlock.

So implement the interface, and then in the setter of the SelectedData property raise the PropertyChanged event:

private MyData _selectedData;
public MyData SelectedData
{
    get { return _selectedData; }
    set
    {
        _selectedData = value;
        RaisePropertyChanged("SelectedData");
    }
}

private void RaisePropertyChanged(string propertyName)
{
    var handler = PropertyChanged;

    if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
}

public event PropertyChangedEventHandler PropertyChanged;

Upvotes: 1

Related Questions