user3530012
user3530012

Reputation: 740

How to create a custom control in code-behind in WPF

I have an issue with creating custom controls in wpf. I always intend to create custom controls completely in code-behind in case I need to extend them.

The issue is when I add them in the xaml they are editable. I don't know how to explain but when I click on them, I can write into them. I think it's the way I'm writing my custom controls. Here's a sample code.

public class MyCustomControl : UserControl
{
    public MyCustomControl()
    {
        var button = new Button();

        this.Content = button;    // I always assign the root element to the Content property of the UserControl. I think this is the case
    }
}

As I said when I add MyCustomControl in Xaml part, it works totally fine but when I click on it (again in xaml part) it is editable and I can write into it. What's my problem exactly?

[Edit] I added screen shots

MyCustomControl in normal state MyCustomControl when I click on and write down into it

this is the code-behind

public class MyCustomControl : UserControl
{
    public MyCustomControl()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        this.Content = new Grid() { Background = Brushes.Red };
    }
}

Upvotes: 0

Views: 2549

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156978

It seems to me you can just overwrite the Content property as it is not locked in any way.

You could add a delegate on the Coerce of the Content and check using a bool check whether it is your code which is editing the control or some external source.

How to do this?

First read these articles:

Then, use something like this:

Control.ContentProperty.OverrideMetadata(typeof(YourControlName), new PropertyMetadata(null, null, yourCallback));

As another option, you could create the Control as Template (define the Control.Template inside the Control). In this way you don't have to depend on the Content property (It won't affect the template). You can even put in the passed in Content if you want, but you don't need to.

Upvotes: 1

Related Questions