2012-03-21 38 views
3

如何创建像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"它呈现的窗口上?这将是很好的为它在设计时不能渲染只是在运行时

+0

您确定您需要一个标签和文本框的自定义控件。您可以将样式应用于Label和TextBox。标签将在设计时渲染。当你添加绑定TextBox的语法时,你不会保存许多按键,而且在我的视图代码中很难遵循。 – Paparazzi 2012-03-21 22:55:54

+0

是的,我试图弄清楚。标签和textox需要在一个堆叠面板内。我试图找出如何为堆叠面板创建一个样式,以便其子代可以拥有特定的样式,而不必为文本框的标签和堆栈面板创建样式。每次我需要一个新的输入字段时,我必须放置三个控件而不是拖动用户控件。 – 2012-03-23 07:37:53

回答

1

我觉得第二种类型的可能InputField 公共静态的DependencyProperty MessageProperty = DependencyProperty.Register( “LblContent”的typeof(串), typeof运算(InputField));最终尝试在usercontrol x:Name =“Root”处给出一个名称,然后像下面这样更改绑定:Content =“{Binding Path = LblContent,ElementName = Root }“

+0

为什么你删除了答案,这是有帮助的大声笑。谢谢 – 2012-03-21 23:07:23

+0

因为我看到您以不同的方式管理datacontext,但我在新帖子中插入了相同的注释。是的,我可以编辑它,你是对的 – pluka 2012-03-22 07:33:44

相关问题