Selecting a Textbox Item in a Listbox does not change the selected item of the listbox

后端 未结 15 1338
清酒与你
清酒与你 2020-11-27 04:10

I Have a wpf Listbox that display\'s a list of textboxes. When I click on the Textbox the Listbox selection does not change. I have to click next to the TextBox to select th

相关标签:
15条回答
  • 2020-11-27 05:04

    Try this code:

    foreach (object item in this.listBox1.Items) {
        if (textbox1.text.equals(item.toString())) {
            //show error message; break
        }
    }
    
    0 讨论(0)
  • 2020-11-27 05:06

    this is the answer you are looking for: Selecting a ListBoxItem when its inner ComboBox is focused

    0 讨论(0)
  • 2020-11-27 05:11

    The simplest way I've been able to find to do this is to use the PreviewMouseDown event and set the IsSelected property of the templated parent. Since the preview events bubble down, the ListBoxItem will process the event as soon as the user clicks the textbox, combobox, or any other control you set the event on.

    One nice thing about this is that you can use the same event for all types of controls since they all derive from Framework element. Also, setting IsSelected (instead of setting the SelectedItem) will cause multiple items to be selected when you set the SelectionMode of the listbox to "Extended", which could or could not be what you're looking for.

    ie:

    c# code

    private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        ((sender as FrameworkElement).TemplatedParent as ListBoxItem).IsSelected = true;
    }
    

    xaml

        ...
        <ComboBox PreviewMouseDown="Element_PreviewMouseDown"/>
        <TextBox PreviewMouseDown="Element_PreviewMouseDown"/>
        ...
    
    0 讨论(0)
提交回复
热议问题