#第一種方法:創建名稱customTextbox.cs類和寫下的文本框
public class customTextbox:TextBox
{
public customTextbox():base()
{
this.AcceptsReturn = true;
this.AllowDrop = true;
this.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
//set your remaining propreties
this.PreviewDragEnter +=customTextbox_PreviewDragEnter;
this.PreviewDragLeave +=customTextbox_PreviewDragLeave;
this.SelectionChanged += customTextbox_SelectionChanged;
}
void customTextbox_SelectionChanged(object sender, System.Windows.RoutedEventArgs e)
{
//code here
}
private void customTextbox_PreviewDragLeave(object sender, System.Windows.DragEventArgs e)
{
//code here
}
private void customTextbox_PreviewDragEnter(object sender, System.Windows.DragEventArgs e)
{
//code here
}
}
,並在XAML
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:hp="clr-namespace:WpfApplication3">
<Grid Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<hp:customTextbox Height="100" Width="100" Grid.Row="0"></hp:customTextbox>
<hp:customTextbox Grid.Row="1" ></hp:customTextbox>
<hp:customTextbox Grid.Row="2" ></hp:customTextbox>
</Grid>
屬性和事件#second方法:創建像這樣(http://prntscr.com/2mren4)一usecontrol並用文本替換用戶控件像下面
<TextBox x:Class="WpfApplication3.CustomTB"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<!--set all properties and event you required inside textbox-->
和cs文件使用文本框,而不是用戶控件像下面
public partial class CustomTB : TextBox
{
public CustomTB()
{
InitializeComponent();
}
}
,並在另一個窗口中添加
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:hp="clr-namespace:WpfApplication3">
<Grid Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<hp:CustomTB Grid.Row="0"/>
</Grid>
您正在尋找'ItemsControl'。除非你有一個很好的理由不要從WPF UI元素繼承。你在這裏描述的不是。 –
所以只需複製粘貼15個文本框...... :( –