如何創建像Textbox一樣的用戶控件?例如,當我更改Textbox控件的Text屬性時,新文本出現在我當前使用的窗口上。將屬性附加到usercontrol並在設計時更新它
在我的項目中,我有很多地方用戶必須輸入信息,因此我想創建一個InputField用戶控件。 (即用戶控件包含一個標籤與自定義樣式的文本框的)
這裏是我的用戶控制的XAML:
<UserControl x:Class="PDV.UserControls.InputField"
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" >
<Grid>
<StackPanel>
<Label Content="{Binding Path=LblContent}" HorizontalAlignment="Left" VerticalAlignment="Top" />
<TextBox Height="23" Margin="5,-5,2,2" Name="textBox1" VerticalAlignment="Top" />
</StackPanel>
</Grid>
</UserControl>
後面爲該用戶控件的代碼:
namespace PDV.UserControls
{
public partial class InputField : UserControl
{
public static DependencyProperty MessageProperty = DependencyProperty.Register(
"LblContent", typeof(string), typeof(UserControl));
public string LblContent{
get{
return (string)GetValue(MessageProperty);
}
set{
SetValue(MessageProperty, value);
}
}
//Constructor
public InputField(){
InitializeComponent();
this.DataContext = this;
}
}
}
所以在我的主窗口中,我將能夠使用該用戶控件:
1)導入用戶控件所在的名稱空間:
xmlns:myCtrl ="clr-namespace:PDV.UserControls"
2)將對照該窗口:
<myCtrl:InputField LblContent="hello" Margin="0,0,483,0" Height="49" VerticalAlignment="Top"></myCtrl:InputField>
什麼我必須這樣做,當我更新LblContent="hello"
它呈現的窗口上?這將是很好的爲它在設計時不能渲染只是在運行時
您確定您需要一個標籤和文本框的自定義控件。您可以將樣式應用於Label和TextBox。標籤將在設計時渲染。當你添加綁定TextBox的語法時,你不會保存許多按鍵,而且在我的視圖代碼中很難遵循。 – Paparazzi 2012-03-21 22:55:54
是的,我試圖弄清楚。標籤和textox需要在一個堆疊面板內。我試圖找出如何爲堆疊面板創建一個樣式,以便其子代可以擁有特定的樣式,而不必爲文本框的標籤和堆棧面板創建樣式。每次我需要一個新的輸入字段時,我必須放置三個控件而不是拖動用戶控件。 – 2012-03-23 07:37:53