Custom controls, TextBox rewrite example

The project may experience rewrite control, under hereby record:

 1 <Window x:Class="WpfApp6.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:WpfApp6"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="157" Width="287">
 9     <Window.Resources>
10         <Style TargetType="local:CustomTextBox">
11             <Setter Property="Template">
12                 <Setter.Value>
13                     <ControlTemplate>
14                         <Grid>
15                             <Grid.ColumnDefinitions>
16                                 <ColumnDefinition />
17                                 <ColumnDefinition Width="auto" />
18                             </Grid.ColumnDefinitions>
19                             <TextBox VerticalContentAlignment="Center" 
20                                      Padding="5"
21                                      Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Text}"/>
22                             <Button x:Name="btnclear" Grid.Column="1" Width="30" Margin="3" Content="清空" />
23                         </Grid>
24                     </ControlTemplate>
25                 </Setter.Value>
26             </Setter>
27         </Style>
28     </Window.Resources>
29     <Grid>
30         <StackPanel>
31             <local:CustomTextBox Text="852"/>
32         </StackPanel>
33     </Grid>
34 </Window>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp6
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }


    public class CustomTextBox : TextBox
    {
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            var btnclear = GetTemplateChild("btnclear") as Button;
            btnclear.Click += Btnclear_Click;
        }

        private void Btnclear_Click(object sender, RoutedEventArgs e)
        {
            Text = string.Empty;
        }
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/xuling-297769461/p/12659450.html