在HierarchicalDataTemplate中绑定FocusedElement

时间:2011-03-15 22:07:41

标签: binding focusmanager

我正在尝试将控件集中在HierarchicalDataTemplate中。不幸的是,我尝试绑定到模板中的控件失败了。这是我的代码:

        <HierarchicalDataTemplate DataType="{x:Type TreeView_Experiment:BookmarkPage}">
            <DockPanel>
                <ToggleButton ... edited for brevity ... />
                <Controls:EditableTextBlock x:Name="EditBox" Text="{Binding Path=Title}" VerticalAlignment="Center" IsEditable="True" Focusable="True"/>
            </DockPanel>
            <HierarchicalDataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=IsFocused, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}" Value="true">
                    <!-- The Value binding fails with the error: Cannot find source for binding with reference 'ElementName=EditBox -->
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=EditBox}"/>
                </DataTrigger>
            </HierarchicalDataTemplate.Triggers>
        </HierarchicalDataTemplate>

当treeview项获得焦点时触发器触发,但{Binding ElementName = EditBox}失败并显示消息“无法找到与引用绑定的源'ElementName = EditBox,...”

如何修复此绑定?或者有更好的方法在HierarchicalDataTemplate中设置控件的焦点吗?

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我能够通过添加这个丑陋的一点代码来实现这一点。将其附加到树视图的onselection已更改:

    private void SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        var treeView = sender as TreeView;

        var selectedContainer =
            typeof (TreeView).GetProperty("SelectedContainer", BindingFlags.NonPublic | BindingFlags.Instance).
                GetValue(treeView, null) as TreeViewItem;

        // Find the element we want to focus.
        var focusControl = selectedContainer.FindVisualChild<TextBox>();
        if (focusControl != null)
            focusControl.Focus();
    }

需要以下扩展方法:

    public static T FindVisualChild<T>(this DependencyObject obj) where T : DependencyObject
    {
        var childCount = VisualTreeHelper.GetChildrenCount(obj);
        for (int i = 0; i < childCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is T)
            {
                return (T)child;
            }

            T childOfChild = FindVisualChild<T>(child);
            if (childOfChild != null)
            {
                return childOfChild;
            }
        }
        return null;
    }

答案 1 :(得分:0)

不是查看TreeView并尝试找到要聚焦的项目,而是让TreeViewItem本身进行聚焦可能会更好。