1

我正在尝试将控件集中在 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>

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

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

提前感谢您的帮助。

4

2 回答 2

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;
    }
于 2011-03-18T16:44:59.230 回答
0

Instead of looking at the TreeView and trying to find the item to focus, it may be better to have the TreeViewItem itself do the focusing.

于 2012-11-18T00:18:33.900 回答