Hi,
I've got a stupid problem with clicking on a custom control (a red grid with a yellow rectangle in the center) in a canvas.
EDIT: The xaml code always gets messed up and truncated. I don't know how to post this properly...
The custom control:
XAML:
<resourcedictionary>
<controltemplate x:key="TESTCONTROL" targettype="{x:Type local:TestControl}">
<grid background="Red">
<rectangle width="50" height="50" verticalalignment="Center"
horizontalalignment="Center" fill="Yellow">
<Setter Property="Template" Value="{StaticResource TESTCONTROL}"/>
Code:
public class TestControl : Control
{
}
There are 2 different cases I've made:
1) Directly adding the custom control to a Canvas:
XAML:
<window>
<canvas x:name="TestCanvas" mouseleftbuttondown="TestCanvas_MouseLeftButtonDown">
Code:
public partial class MyWindow : Window
{
public MainWindow()
{
InitializeComponent();
TestControl control = new TestControl();
control.Width = 100;
control.Height = 100;
TestCanvas.Children.Add(control);
}
}
2) Using an ItemsControl with a Canvas as ItemPanel (ItemsSource + List)
XAML:
<window>
<itemscontrol x:name="TestItemsCtrl">
<itemscontrol.itemspanel>
<itemspaneltemplate>
<canvas mouseleftbuttondown="TestCanvas_MouseLeftButtonDown">
Code:
public partial class MyWindow : Window
{
public MainWindow()
{
InitializeComponent();
TestControl control = new TestControl();
List<testcontrol> controlList = new List<testcontrol>();
controlList.Add(control);
TestItemsCtrl.ItemsSource = controlList;
}
}
Now if I start the program and click on the control I check the e.Source/e.OriginalSource argument:
private void TestCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Title = e.Source.GetType().Name;
}
For case 1 this displays "TestControl" no matter where I click on my TestControl. This is my desired behaviour.
For case 2 this displays the class name of whatever part of "TestControl" I clicked on. ("Grid" or "Rectangle").
Why does this difference exist and what can I do to get the whole TestControl instead of its parts while still using an ItemsControl?
What I have tried:
I've tried an ItemTemplate with my ItemsControl altough I don't need one/shouldn't need one because the ItemsSource contains controls itself so there is no need for a template in this case.
I've tried attaching the event to the ItemsControl instead of the Canvas (ItemsPanel).
This didn't make any meaningful difference. (Except source contained e.Source contained the ItemsControl itself and e.OriginalSource contained the Grid/Rectangle parts of my TestControl instead of the TestControl itself.