.net 显示列表框SelectedItem

.net 显示列表框SelectedItem,.net,wpf,.net,Wpf,我刚刚读过,我对它的实现有问题 主窗口的列表框中有一些数据。在列表框内的选定项上,我希望在同一窗口状态栏的textblock中显示选定的数据是DataOne,其中DataOne表示名称属性 MainWindow.xaml <ListBox Name="listBoxData" ItemsSource="{Binding MyListBoxData}" SelectedItem="{Binding SelectedData}" /> p、

我刚刚读过,我对它的实现有问题

主窗口的列表框中有一些数据。在列表框内的选定项上,我希望在同一窗口状态栏的textblock中显示选定的数据是DataOne,其中DataOne表示名称属性

MainWindow.xaml

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

p、 为了澄清数据是否正确显示在列表框中,DataContext设置在ViewModel构造函数中。

看起来您没有在ViewModel中实现接口

必须这样做,绑定系统才能知道何时更新
文本块中的值

因此,实现接口,然后在
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;

您应该能够直接绑定到
MyListBoxData
集合中的选定项,如下所示:

<TextBlock Text="{Binding MyListBoxData/Name, StringFormat='Selected data is: {0}'}">
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;
<TextBlock Text="{Binding MyListBoxData/Name, StringFormat='Selected data is: {0}'}">
<ListBox Name="listBoxData" IsSynchronizedWithCurrentItem="True"             
    ItemsSource="{Binding MyListBoxData}" />