0

我有User control一个list box

User control位于我的窗口。如何从用户控件的列表框中检测并获取所选项目?

我以前试过这个,但是当我从列表框e.OriginalSource返回TextBlock类型中选择一个项目时。

  private void searchdialog_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //This return TextBlock type
            var conrol= e.OriginalSource;
            //I Want something like this
            if (e.OriginalSource is ListBoxItem)
            {
                ListBoxItem Selected = e.OriginalSource as ListBoxItem;
                //Do somting
            }
        }

或者有什么更好的方法可以SelectionChanged从我的表单中检测列表框?

4

2 回答 2

3

我认为最好的解决方案是在您的用户控件上声明一个事件,只要在SelectedValueChanged列表框上触发该事件就会触发该事件。

public class MyUserControl : UserControl
{
  public event EventHandler MyListBoxSelectedValueChanged;

  public object MyListBoxSelectedValue
  {
    get { return MyListBox.SelectedValue; }
  }

  public MyUserControl()
  {
    MyListBox.SelectedValueChanged += MyListBox_SelectedValueChanged;
  }

  private void MyListBox_SelectedValueChanged(object sender, EventArgs eventArgs)
  {
    EventHandler handler = MyListBoxSelectedValueChanged;
    if(handler != null)
      handler(sender, eventArgs);
  }
}

在您的窗口中,您侦听事件并使用用户控件中的公开属性。

public class MyForm : Form
{
  public MyForm()
  {
    MyUserControl.MyListBoxSelectedValueChanged += MyUserControl_MyListBoxSelectedValueChanged;
  }

  private void MyUserControl_MyListBoxSelectedValueChanged(object sender, EventArgs eventArgs)
  {
    object selected = MyUserControl.MyListBoxSelectedValue;
  }
}
于 2012-12-19T09:47:44.223 回答
1

有几种方法可以处理这个问题:

  1. 在您的用户控件中实现 SelectionChanged 事件,并引发您在窗口中处理的自定义事件:

    //在你的用户控件中

    private void OnListBoxSelectionChanged(object s, EventArgs e){
        if (e.AddedItems != null && e.AddedItems.Any() && NewItemSelectedEvent != null){   
            NewItemsSelectedEvent(this, new CustomEventArgs(e.AddedItems[0]))
        }
    }
    

    //在你的窗口中

    myUserControl.NewItemsSelected += (s,e) => HandleOnNewItemSelected();
    
  2. 如果您使用绑定或任何形式的 MVVM,您可以使用 aDependencyProperty将所选项目绑定到视图模型中的对象

    //在你的用户控件中:

    public static readonly DependencyProperty CurrentItemProperty = 
     DependencyProperty.Register("CurrentItem", typeof(MyListBoxItemObject), 
    typeof(MyUserControl), new PropertyMetadata(default(MyListBoxItemObject)));
    
    public LiveTextBox CurrentItem
    {
        get { return (MyListBoxItemObject)GetValue(CurrentItemProperty ); }
        set { SetValue(CurrentItemProperty , value); }
    }
    

    //在你的窗口xaml中

    <MyUserControl CurrentItem={Binding MyCurrentItem} ... />
    
于 2012-12-19T09:49:54.480 回答