【问题标题】:How to create a custom control in code-behind in WPF如何在 WPF 的代码隐藏中创建自定义控件
【发布时间】:2014-05-09 08:30:58
【问题描述】:

我在 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 部分中)它是可编辑的,我可以写入它。我到底有什么问题?

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

这是代码隐藏

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

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

【问题讨论】:

  • 你能提供你的问题的截图吗?
  • 当然。我添加了截图@samar。

标签: c# wpf custom-controls


【解决方案1】:

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

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

如何做到这一点?

首先阅读这些文章:

然后,使用这样的东西:

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

作为另一种选择,您可以将Control 创建为Template(在Control 中定义Control.Template)。这样您就不必依赖Content 属性(它不会影响模板)。如果你愿意,你甚至可以输入传入的Content,但你不需要。

【讨论】:

  • 这是个好主意。我理解您的意思,但是我不知道如何实现“添加委托检查它是您的代码还是某些外部源”部分。你能给我一个样品吗?
  • @user3530012:找到了一些如何做到这一点的来源。查看更新的答案。
  • 那么问题是可以从 xaml 访问 Content 属性。我找到了一个解决方案来隐藏 xaml 部分的属性,即使用 EditorBrowsable 属性。但它不适用于继承的属性。我试图覆盖属性设置器(通过使用 new 关键字)但 id 也没有帮助。
  • @user3530012:XAML 依赖于 DependencyProperties,所以你被困在那里。我会添加另一个选项。
  • @user3530012:我上次的更新对你有帮助吗?你被困在哪里了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
相关资源
最近更新 更多