从ListBox WPF .NET 3.5中选择的值

时间:2013-09-12 22:55:33

标签: c# wpf .net-3.5 listbox

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

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

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

感谢。

1 个答案:

答案 0 :(得分: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));
        }
    }

}