繁体   English   中英

如何在WPF中的代码隐藏中创建自定义控件

[英]How to create a custom control in code-behind in WPF

我在wpf中创建自定义控件时遇到问题。 我总是打算在代码背后完全创建自定义控件,以防我需要扩展它们。

问题是,当我将它们添加到xaml中时,它们是可编辑的。 我不知道该怎么解释,但是当我点击它们时,我可以写出来。 我认为这就是我编写自定义控件的方式。 这是示例代码。

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
    }
}

就像我说的那样,当我在Xaml部分中添加MyCustomControl时,它完全可以正常工作,但是当我单击它时(同样在xaml部分中),它是可编辑的并且可以写入其中。 我到底有什么问题?

[编辑]我添加了屏幕截图

MyCustomControl处于正常状态当我单击并写下来时为MyCustomControl

这是背后的代码

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

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

在我看来,您可以覆盖Content属性,因为它没有以任何方式锁定。

您可以在ContentCoerce上添加一个委托,然后使用bool检查是否是您的代码在编辑控件或某些外部源。

这个怎么做?

首先阅读这些文章:

然后,使用如下代码:

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

作为另一个选项,您可以创建ControlTemplate (定义Control.Template内部Control )。 这样,您不必依赖Content属性(它不会影响模板)。 如果需要,您甚至可以放入传递的Content ,但不需要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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