简体   繁体   中英

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处于正常状态当我单击并写下来时为MyCustomControl

this is the code-behind

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM