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 ListBoxItem 不会拉伸(stretch)到最大宽度

wpf - 为什么 AdornerLayers 总是最顶层?有没有办法改变它?

c# - 在 WPF ListView 中拖放

c# - 绑定(bind)源更新后如何执行 ICommand?

xaml - "Hello World",ReactiveUI、Xamarin Forms 和 XAML 锁定

c# - 设置 ASP.NET (4.0) 列表框的宽度和高度以适合项目

c# - 检测是否在 C# 中按下了任何键(不是 A、B,而是任何键)

c# - WPF 工具包 Datagrid - 如何关闭选择?

wpf - 使 ListBox 项目可编辑

.net - 反转 ListBox 项目(按 "nothing"降序排序)