2014-01-06 60 views
1

我剛剛讀了this question,我在執行時遇到問題。顯示列表框SelectedItem

MainWindow有一些數據的列表框。在該列表框中的選定項目上,我希望在同一窗口的狀態欄上的文本塊中顯示選定的數據是DataOne,其中DataOne表示Name屬性。

MainWindow.xaml

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

內部狀態欄元素

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

MainWindowViewModel

public MyData SelectedData {get; set;} 

附:只是爲了澄清數據在列表框內正確顯示,DataContext是在ViewModel構造函數內部設置的。

回答

1

看起來你沒有在viewmodel中實現接口INotifyPropertyChanged

您必須這樣做才能讓綁定系統知道何時更新TextBlock中的值。

所以實現接口,然後在SelectedData setter方法提高PropertyChanged事件:

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; 
1

您應該能夠直接從MyListBoxData收集像這樣綁定到選定的項目:

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

如果起初不工作,你可能需要設置在ListBoxTrueIsSynchronizedWithCurrentItem屬性:

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