在WPF自定义控件中添加按钮

本文关键字:添加 按钮 自定义控件 WPF | 更新日期: 2023-09-27 17:58:41

我是WPF的新手,正在编写一个simlpe WPF自定义控件。以下是我的代码。

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 textbtn
{
    public class CustomControl1 : Control
    {
        static CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
        }        
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //if (test.Width > 50)
            //    test.Width = 0;
            //else          
            //    test.Width = 100;
        }
    }
}

我的XAML代码:

<ResourceDictionary
    x:Class="textbtn.CustomControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:textbtn">
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <Button Content="CButton" Height="23" HorizontalAlignment="Center" Name="button1" VerticalAlignment="Center" Width="75" Click="button1_Click"/>
                            <TextBlock Text="This is a Test" Foreground="Aqua" Background="AntiqueWhite" />
                        </Grid>
                    </Border>                    
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

我得到以下错误。请帮我修一下。提前谢谢。

错误1"textbtn"类型的声明中缺少分部修饰符。CustomControl1';该类型的另一个部分声明存在

在WPF自定义控件中添加按钮

更换

public class CustomControl1 : Control

有了这个:

public partial class CustomControl1 : Control