TreeNode Selection Problems in C#
Whenever I click outside the tree nodes text, on the control part, it tigers a node click event- but doesn't highlight开发者_开发知识库 the node. I am unsure why this is happening.
I want the node to be selected on a click- when you click the nodes text- not the whitespace- I only assume that the nodes width reaches across the whole Treenode? I have the Treeview on dock.fill mode if that has something to do with it- I tried everything but can't get it to behave correctly.
Maybe someone will know what's going on.
Update:
if (e.Location.IsEmpty)
{
Seems to work better- but still selects the node in the blank place where there is no text- Obviously the node width extends across the whole treeview it seems?
Is there a better way to accomplish what I want? Or is that the best way?
UPDATE: Previous idea isn't working- sigh- I thought it did it but it didn't.
New Problem : I think part of the problem is related to the focus now when I switch from treeview.
UPDATE-
The only code I came up with about disabling right mouse click to select node on beforeSelect event is
if (MouseButtons == System.Windows.Forms.MouseButtons.Right)
{
e.Cancel = true;
}
But it didn't work- any help is appreciated- following suggestions of only answer, for more details.
You should use the treeView.HitTest method to determine which part of the node has been clicked.
private bool IsClickOnText(TreeView treeView, TreeNode node, Point location)
{
var hitTest = treeView1.HitTest(location);
return hitTest.Node == node
&& hitTest.Location == TreeViewHitTestLocations.Label;
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if(IsClickOnText(treeView1, e.Node, e.Location))
{
MessageBox.Show("click");
}
}
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
var position = treeView1.PointToClient(Cursor.Position);
e.Cancel = !IsClickOnText(treeView1, e.Node, position);
}
}
Use the .AfterSelect and/or .BeforeSelect events to handle the selection processing instead of the .Click event. Then it will select the node only when you click on the text, and it won't fire .AfterSelect or .BeforeSelect when you click on the white space.
精彩评论