【问题标题】:How can I put a custom control's class inside another custom control?如何将自定义控件的类放在另一个自定义控件中?
【发布时间】:2013-05-13 06:51:50
【问题描述】:

假设我已经像这样编写了一个自定义Canvas

public class MyCustomControl : Canvas
    {
        public MyCustomControl()
        {
            this.Background = System.Windows.Media.Brushes.LightBlue;
        }
    }

我需要在其中放入另一个自定义编码(自定义控件)Label,并将整个项目用作另一个项目中的一个自定义控件。

我这样做了:

public class MyCustomControl : Canvas
    {
        public MyCustomControl()
        {
            this.Background = System.Windows.Media.Brushes.LightBlue;
        }
       //My custom label
        public class MyLabel : Label
        {
            public MyLabel()
            {
                Content = "Hello!!";
                Width = 100;
                Height = 25;
                VerticalAlignment = System.Windows.VerticalAlignment.Center;
                HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            }
        }
    }

但我在 OTHER 项目中看不到 Label。看图片:

由于我在第一个项目中创建了一个自定义控件,因此我没有可以依赖的视觉参考(如 XAML 设计窗口或其他任何东西),基本上是通过查看所有元素都正确编码和可见。

首先,我不知道这是否是创建嵌套自定义控件的正确方法。 其次,我不知道为什么那里没有显示标签。可能是因为我必须将它添加到画布中。但我不知道将标签添加到其父级(即画布)的代码。

【问题讨论】:

    标签: wpf class nested custom-controls


    【解决方案1】:

    将标签添加到画布:

    public MyCustomControl()
    {
        this.Background = System.Windows.Media.Brushes.LightBlue;
        this.Children.Add(new MyLabel());
    }
    

    但在这种情况下,您不需要自定义标签:

    public MyCustomControl()
    {
        this.Background = System.Windows.Media.Brushes.LightBlue;
        this.Children.Add(new Label{
            Content = "Hello!!",
            Width = 100,
            Height = 25,
            VerticalAlignment = System.Windows.VerticalAlignment.Center,
            HorizontalAlignment = System.Windows.HorizontalAlignment.Center
        });
    }
    

    如果您希望能够设计您的 Canvas,请将 UserControl 添加到您的第一个项目中。

    <UserControl ...>
        <Canvas Background="LightBlue">
            <Label Width="100" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center">
                Hello!!
            </Label>
        </Canvas>
    </UserControl>
    

    【讨论】:

    • 非常感谢!现在得去测试它;)编辑:它有效!非常感谢 Lisp ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多