folibis
folibis

Reputation: 12874

WPF Custom control based on Canvas, where can I place the initiation code?

I've just created a new project in VS - Custom Control. The control is Canvas based since I need some drawing. The code is mostly auto generated so I will not provide here all the project.

My target is to bind some events/handlers of the control. Unfortunately I didn't find any constructor. After searching the Internet I found a way to do that - to put the init code inside the OnApplyTemplate() overridden method. As for me it is strange idea to avoid constructor, or some init method, but anyway .... Ok, I know that logic is not MS prerogative, no problem. But the real problem is that this method never called. So my question - where should I put my init code or (if OnApplyTemplate the only option) how to make this method be called on the component start?

MyMap.cs

namespace MyControl
{
public class MyMap : Canvas
{
    public static readonly DependencyProperty ZoomProperty = DependencyProperty.Register("Zoom",
    typeof(float),
    typeof(MyMap),
    new PropertyMetadata(0.5f));

    public float Zoom
    {
        get { return (float)GetValue(ZoomProperty); }
        set { SetValue(ZoomProperty, value); }
    }

    static MyMap()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyMap), new FrameworkPropertyMetadata(typeof(MyMap)));                        
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        this.SizeChanged += Map_SizeChanged;
    }
}
}

The Themes/Generic.xaml file content:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyControl">

</ResourceDictionary>

The AssemblyInfo.cs has the following lines:

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None,
    ResourceDictionaryLocation.SourceAssembly 
)]

Upvotes: 0

Views: 675

Answers (1)

Clemens
Clemens

Reputation: 128146

Just add a constructor like this:

public class MyMap : Canvas
{
    public MyMap()
    {
        SizeChanged += Map_SizeChanged;
    }

    ...
}

Upvotes: 2

Related Questions