你好我是wpf c#的新手,我有一个在运行时填充的树视图,这是我的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>
当我右键单击树视图中的文本块时,我想要的是什么。文本块需要关注。截至目前,它的作用是显示上下文菜单项。
那么如何获取右键单击文本块的索引?所以我可以专注于那个项目。 谢谢
答案 0 :(得分:1)
TextBlock无法聚焦...但您可以通过转换sender参数在MouseRightButtonDown事件处理程序中获取对它的引用:
private void TextBlock_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
TextBlock txt = sender as TextBlock;
//do whatever you want with the TextBlock...
}
如果您在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);
}