0

我的 WPF 应用程序中有一个列表框。定义如下:

<ListBox Margin="17.493,33.32,22.491,26.656" Name="lstData"   
                 PreviewMouseLeftButtonDown="ListBox_MouseDown"
                 IsTextSearchEnabled="False" />

在后面的代码中,我将 ListBox 绑定到一个 List。当从列表框中选择值时,在我后面的代码中,我希望能够检索该值。我该怎么做?示例 C# 代码将很有帮助。

谢谢。

4

1 回答 1

0

您可以绑定到后面代码中的一个项目

例子:

<ListBox Margin="17.493,33.32,22.491,26.656" Name="lstData"   
         SelectionChanged="ListBox_selectionChanged"
         IsTextSearchEnabled="False"
         ItemsSource="{Binding MyItems}"
         SelectedItem="{Binding MySelectedItem}"/>


public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {  
        InitializeComponent();
        DataContext = this;
    }

    private ObservableCollection<MyItemType> _myItems = new ObservableCollection<MyItemType>();
    public ObservableCollection<MyItemType> MyItems
    {
        get { return _myItems; }
        set { _myItems = value; }
    }

    private MyItemType _mySelectedItem;
    public MyItemType MySelectedItem
    {
        get { return _mySelectedItem; }
        set { _mySelectedItem = value; NotifyPropertyChanged("MySelectedItem"); }
    }

    private void ListBox_selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show(_mySelectedItem);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string p)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(p));
        }
    }

}
于 2013-09-12T23:01:33.643 回答