wpf - 在其内部 ComboBox 获得焦点时选择 ListBoxItem

标签 wpf xaml listbox datatemplate triggers

我有一个 DataTemplate,它将是一个模板化的 ListBoxItem,这个 DataTemplate 有一个
其中的 ComboBox 当它有焦点时我想要这个模板的 ListBoxItem
代表被选中,这对我来说是正确的。但遗憾的是它不起作用=(

所以这里真正的问题是在 DataTemplate 中是否可以获取或设置值
ListBoxItem.IsSelected属性(property)通过 DataTemplate.Trigger ?

<DataTemplate x:Key="myDataTemplate" 
              DataType="{x:Type local:myTemplateItem}">

 <Grid x:Name="_LayoutRoot">
     <ComboBox x:Name="testComboBox" />
 </Grid>

 <DataTemplate.Triggers>
     <Trigger Property="IsFocused" value="true" SourceName="testComboBox">
         <Setter Property="ListBoxItem.IsSelected" Value="true" />
     </Trigger>
 </DataTemplate.Triggers>

</DataTemplate>

<ListBox ItemTemplate="{StaticResource myDataTemplate}" />

最佳答案

我为您的问题找到了解决方案。

问题是,当您在 listboxitem 上有一个控件,并且单击该控件时(例如输入文本或更改组合框的值),ListBoxItem 不会被选中。

这应该可以完成这项工作:

public class FocusableListBox : ListBox
{
    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return (item is FocusableListBoxItem);
    }

    protected override System.Windows.DependencyObject GetContainerForItemOverride()
    {
        return new FocusableListBoxItem();
    }
}

--> 使用此 FocusableListBox 代替 WPF 的默认 ListBox。

并使用这个 ListBoxItem:
public class FocusableListBoxItem : ListBoxItem
{
    public FocusableListBoxItem()
    {
        GotFocus += new RoutedEventHandler(FocusableListBoxItem_GotFocus);
    }


    void FocusableListBoxItem_GotFocus(object sender, RoutedEventArgs e)
    {
        object obj = ParentListBox.ItemContainerGenerator.ItemFromContainer(this);
        ParentListBox.SelectedItem = obj;
    }

    private ListBox ParentListBox
    {
        get
        {
            return (ItemsControl.ItemsControlFromItemContainer(this) as ListBox);
        }
    }

}

一个 Treeview也有这个问题,但是这个解决方案对 Treeview 不起作用, 因为 SelectedItemTreeviewreadonly .
所以,如果你能帮我解决 Treeview 问题,请 ;-)

关于wpf - 在其内部 ComboBox 获得焦点时选择 ListBoxItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1459786/

相关文章:

c# - 如何在 wpf 中为 TreeView 进行文本换行

c# - VSIX 窗口 - 执行 ICommand 的快捷键

wpf - 如何使用 Button、Extender 和 ListBox 制作 "SelectButton"以获得所需的宽度?

c# - 如何使用 c#.net 在桌面应用程序中使列表框文本居中对齐

wpf - 将弹出窗口位置锁定到元素,或伪造带有图层的弹出窗口以在 ItemsControl 中进行就地编辑

c# - MVVM Caliburn.micro 组合框 Country-City 无法正常工作

c# - 如何获取元素的父元素?

xaml - 在 Windows 8.1 存储 XAML 中添加新项目后,ListView.ContainerFromItem 返回 null

c# - 选择单个单选按钮,wpf

c# - 字典与列表与数组的速度和功能