如何定义控件的自定义类,并在其中定义自定义事件和处理程序(在WPF中)?

Ali*_*Ali 0 wpf events inheritance winforms

我是WPF和Windows Forms的新手.我需要知道我怎么能自定义一个类的控件(如标签或文本框...),并定义它的长相我写的自定义方法是控制的任何所需的事件.就像点击标签周围的黑色边框一样.

我需要做的这一切SO,我可以动态创建该类的多个实例,因为我想,确保它们都具有相同的功能,并且我把他们的样子.

有没有关于这个的简单教程?

Mar*_*kus 5

你要找的是从已经存在的控件(CustomControl)继承os创建一个新的控件,你可以添加一个控件(UserControl).如果它应该是一个控件的自定义类(如Label或TextBox),那么我会尝试使用CustomControl来解决它

WinForms和WPF的名称相同.我可以提供一些链接,但我认为你最好只是google它,这样你就可以找到最适合你需求的示例/教程.

编辑

好吧,所以我会说 - 根据你的背景 - WinForms更简单一些.但是,如果您制作专业课程,WPF可能就是您的选择.(WinForms有点老了)

WinForm的

至少在这里,是一个非常简短的WinForm CustomControl示例:

namespace BorderLabelWinForms
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Drawing;

    public class BorderLabel : Label
    {
        private bool _showBorder = false;

        protected override void OnMouseClick(MouseEventArgs e)
        {
            _showBorder = !_showBorder;
            base.OnMouseClick(e);
            this.Refresh();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (_showBorder)
            {
                Pen pen = new Pen(new SolidBrush(Color.Black), 2.0f);
                e.Graphics.DrawRectangle(pen, this.ClientRectangle);
                pen.Dispose();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以从那里开始并扩展它.

WPF

WPF更复杂,但要创建CustomControl,请在项目视图中右键单击项目,然后选择"添加">"新建项".在弹出的对话框中,选择自定义控件(WPF).现在,您将获得一个新的{选择名称} .cs(在我的示例中为BorderLable)和一个目录; 主题和Generic.xaml文件.通用文件是描述控件构建方式的资源.例如,我在CustomControl中添加了一个Label:

Generic.xaml:

    <Style TargetType="{x:Type local:BorderLabel}">
        <Style.Resources>
            <local:ThicknessAndBoolToThicknessConverter x:Key="tabttc" />
        </Style.Resources>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:BorderLabel}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}" >
                        <Border.BorderThickness>
                            <MultiBinding Converter="{StaticResource tabttc}" >
                                <Binding Path="BorderThickness" RelativeSource="{RelativeSource TemplatedParent}" />
                                <Binding Path="ShowBorder" RelativeSource="{RelativeSource TemplatedParent}" />
                            </MultiBinding>
                        </Border.BorderThickness>
                        <Label Content="{TemplateBinding Content}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

BorderLable.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BorderButton
{
    /// <summary>
    /// Bla. bla bla...
    /// </summary>
    public class BorderLabel : Label
    {
        //DependencyProperty is needed to connect to the XAML
        public bool ShowBorder
        {
            get { return (bool)GetValue(ShowBorderProperty); }
            set { SetValue(ShowBorderProperty, value); }
        }

        public static readonly DependencyProperty ShowBorderProperty =
            DependencyProperty.Register("ShowBorder", typeof(bool), typeof(BorderLabel), new UIPropertyMetadata(false));

        //Override OnMouseUp to catch the "Click". Toggle Border visibility
        protected override void OnMouseUp(MouseButtonEventArgs e)
        {
            base.OnMouseUp(e);
            ShowBorder = !ShowBorder;
        }

        //Contructor (some default created when selecting new CustomControl)
        static BorderLabel()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(BorderLabel), new FrameworkPropertyMetadata(typeof(BorderLabel)));
        }
    }

    //So doing it the WPF way, I wanted to bind the thickness of the border
    //to the selected value of the border, and the ShowBorder dependency property
    public class ThicknessAndBoolToThicknessConverter : IMultiValueConverter
    {

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values[0] is Thickness && values[1] is bool)
            {
                Thickness t = (Thickness)values[0];
                bool ShowBorder = (bool)values[1];

                if (ShowBorder)
                    return t;
                else
                    return new Thickness(0.0d);

            }
            else
                return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您必须将控件添加到MainWindow:

<Window x:Class="BorderButton.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BorderButton"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <!-- Note that the BorderThickness has to be set to something! -->
        <local:BorderLabel Content="HelloWorld" Margin="118,68,318,218" MouseUp="BorderLabel_MouseUp" BorderBrush="Black" BorderThickness="2" ShowBorder="False" />
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,WPF有点复杂......无论如何,现在你有两个例子可以开始!希望能帮助到你.