简体   繁体   English

wpf textblock专注于鼠标右键单击

[英]wpf textblock focus on mouse right click

hello I am pretty new to wpf c#, I have a treeview which is populated at run time and here is my xaml code 你好,我是wpf c#的新手,我有一个运行时填充的treeview,这是我的xaml代码

<StackPanel Orientation="Horizontal">
    <Image Source="Properties\accessories-text-editor-6.ico" Margin="0,0,5,0" />
    <TextBlock Text="{Binding Name}" Foreground="Green" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" MouseRightButtonDown="TextBlock_MouseRightButtonDown" >
        <TextBlock.ContextMenu>
            <ContextMenu>
                <MenuItem Header="HeadLine" ></MenuItem>
                <MenuItem Header="Textblock" ></MenuItem>
                <MenuItem Header="Author" ></MenuItem>
                <MenuItem Header="PageNumber" ></MenuItem>
                <MenuItem Header="RunningTitle" ></MenuItem>
                <MenuItem Header="Illustration" ></MenuItem>
            </ContextMenu>
        </TextBlock.ContextMenu>
    </TextBlock>
</StackPanel>

what I want is when I right click the textblock that is inside the treeview. 我想要的是当我右键单击树视图中的文本块时。 the textblock need to be focus. 文本块需要重点关注。 As of now what it does is show the context menu item. 到目前为止,它所做的是显示上下文菜单项。

so how do I get the index of the Right clicked textblock? 那么如何获取右键单击文本块的索引? so I can focus to that item. 所以我可以专注于那个项目。 Thank you 谢谢

A TextBlock cannot be focused...but you can get a reference to it in the MouseRightButtonDown event handler by casting the sender argument: 无法锁定TextBlock ...但是您可以通过转换sender参数在MouseRightButtonDown事件处理程序中获取对它的引用:

private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TextBlock txt = sender as TextBlock;
    //do whatever you want with the TextBlock...
}

If you are in the context of a TreeView you may want to select the parent TreeViewItem: 如果您处于TreeView的上下文中,则可能要选择父级TreeViewItem:

private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    TextBlock txt = sender as TextBlock;
    TreeViewItem tvi = FindParent<TreeViewItem>(txt);
    if (tvi != null)
        tvi.IsSelected = true;
}

private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null) return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM