пятница, 21 августа 2009 г.

HitTest for WPF Tree

Not so far we started to convert our application GUI to WPF technology. We needed treeview with multiselection.

Standart WPF tree do not support multiselection, so I had to do it by my own.

In this note I'd like to tell how to implement HitTest in WPF tree.

I've got the simple class, ingerited from TreeView

public class MultiSelectTreeView : TreeView

I've got to handle Control key to allow multiselection

bool IsCtrlPressed
{
get
{
return Keyboard.IsKeyDown(Key.LeftCtrl)
|| Keyboard.IsKeyDown(Key.RightCtrl);
}
}

We add our own functionality to OnMouseUp method (just believe me, handle OnMouseDown - that's a bad idea)

In my tree I use Model-View-ViewModel pattern - and ItemViewModel class is the ViewModel for my tree. (More info about it: here)

protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);

ItemViewModel selectedItem =
GetItemAtLocation(e.GetPosition(this));
if (selectedItem != null)
this.SelectItem(selectedItem);
}

Let's have a look at GetItemAtLocation(Point point) method. The HitTest is used right here. Terribly simple:

private ItemViewModel GetItemAtLocation(Point point)
{
HitTestResult hitTestResult =
VisualTreeHelper.HitTest(this, point);
if (hitTestResult.VisualHit is FrameworkElement)
{
FrameworkElement element =
hitTestResult.VisualHit as FrameworkElement;
return element.DataContext as ItemViewModel;
}
return null;
}

среда, 19 августа 2009 г.

How to know if .Net application is running under debugger

In my application I've got the bug reporting. When an unhandled error occurs - it show the form to let user send the report.

That's good for user, not for developper, because he needs to handle unhandled exceptions with debugger, cuz it's much more informative.

So, we need to lock bug reporting when application is under debugger.

Here's the solution:


if (!Debugger.IsAttached)
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler
(CurrentDomain_UnhandledException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler
(Application_ThreadException);
}



P.S. To use the Debugger class you need using System.Diagnostics namespace