Search code examples
c#wpfuser-controlsselectionchanged

Get selected List Box item in user control from Window


I have a User control with a list box.

This User control located on my window. how can I detect and get selected item from list box in user control?

I previously tried this but when i select an item from list box e.OriginalSource return TextBlock type.

  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
            }
        }

Or there is any better way that I detect list box SelectionChanged in From My form?


Solution

  • I think the best soution would be to declare an event on your user control, that is fired whenever the SelectedValueChanged event is fired on the listbox.

    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);
      }
    }
    

    In your window, you listen to the event and use the exposed property in the user control.

    public class MyForm : Form
    {
      public MyForm()
      {
        MyUserControl.MyListBoxSelectedValueChanged += MyUserControl_MyListBoxSelectedValueChanged;
      }
    
      private void MyUserControl_MyListBoxSelectedValueChanged(object sender, EventArgs eventArgs)
      {
        object selected = MyUserControl.MyListBoxSelectedValue;
      }
    }