項目中可能會遇到重寫控制項的情況,特此記錄下: 1 <Window x:Class="WpfApp6.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://sc ...
項目中可能會遇到重寫控制項的情況,特此記錄下:
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>
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents; 10 using System.Windows.Input; 11 using System.Windows.Media; 12 using System.Windows.Media.Imaging; 13 using System.Windows.Navigation; 14 using System.Windows.Shapes; 15 16 namespace WpfApp6 17 { 18 /// <summary> 19 /// MainWindow.xaml 的交互邏輯 20 /// </summary> 21 public partial class MainWindow : Window 22 { 23 public MainWindow() 24 { 25 InitializeComponent(); 26 } 27 } 28 29 30 public class CustomTextBox : TextBox 31 { 32 public override void OnApplyTemplate() 33 { 34 base.OnApplyTemplate(); 35 36 var btnclear = GetTemplateChild("btnclear") as Button; 37 btnclear.Click += Btnclear_Click; 38 } 39 40 private void Btnclear_Click(object sender, RoutedEventArgs e) 41 { 42 Text = string.Empty; 43 } 44 } 45 }