选中ListBoxItem中的TextBox后,如何改变ListBox的SelectedItem?

【问题提出】


【ItemView.xaml】:
一个UserControl x:Name="listBoxItemView" 完成ListBoxItem外观的定制,因为外观内容较多,就没有用DataTemplate直接定义外观。
该UserControl 内部有一个TextBox

【全局定义】

  


【添加ListBox】


TaskViewModel为TaskList集合的项!
如何在UserControl中的TextBox获得输入焦点时,把ListBox 对应的ListBoxItem也置为选中呢?


===============================================================================

方法一:

                 ItemsSource="{Binding TaskList}" HorizontalContentAlignment="Stretch">

    

        

            

        

    


protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)

{

    ListBoxItem item = (ListBoxItem)sender;

    item.IsSelected = true;

}


方法二:       

 

            

                

                    

                

            

        


UIElement.IsKeyboardFocusWithin Property


Gets a value indicating whether keyboard focus is anywhere within the element or its visual tree child elements. This is a dependency property. more


这两种方法来自: 

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



对比之下第二种方法比较简单(采用属性操作)。

而第一种方法(采用事件方式)需要添加事件处理代码,但很好的利用了路由事件的优势,

尤其是:

SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)

sender是直接指向的ListBoxItem的,而这种原始的事件触发者是Virual Tree中的元素



后话: 我的例子中用到了的ListBoxItem的外观用到了Checkbox comboBoxtextboxbutton等,如果想再点击每一个子元素时,listboxselecteditem都能发生改变,就必须在这些子元素上添加:

Focusable="True"

不然有些控件比如CheckBox,就不能达到要求。

而这样就会出现虚框了,此时,再加入:

FocusVisualStyle="{x:Null}"

就可以去掉虚框了!


这样就完美了!

你可能感兴趣的:(C#/WPF)