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
Old discussion, but maybe my answer helps others....
Ben's solution has the same problem as Grazer's solution. The bad thing is that the selection depends on the [keyboard] focus of the textbox. If you have another control on your dialog (i.e. a button) the focus gets lost when clicking the button and the listboxitem becomes un-selected (SelectedItem == null). So you have different behavior for clicking the item (outside the textbox) and clicking in the textbox. This is very tedious to handle and looks very strange.
I'm quite sure there is no pure XAML solution for this. We need code-behind for this. The solution is close to what Mark suggested.
(in my example I use ListViewItem instead of ListBoxItem, but the solution works for both).
Code-behind:
private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var frameworkElement = sender as FrameworkElement;
if (frameworkElement != null)
{
var item = FindParent(frameworkElement);
if (item != null)
item.IsSelected = true;
}
}
with FindParent (taken from http://www.infragistics.com/community/blogs/blagunas/archive/2013/05/29/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight.aspx ):
public static T FindParent(DependencyObject child) where T : DependencyObject
{
//get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
return parent;
return FindParent(parentObject);
}
In my DataTemplate: