简体   繁体   中英

Attach property to usercontrol and updating it at design time

How can I create a user control like the Textbox? For example when I change the Text property of a Textbox control the new text appears on the window that I am currently working with.

In my project I have a lot of places where the user has to enter information therefore I want to create a InputField user control. (that usercontrol consists of a label an a textbox with custom style)

Here is the xaml for my user control:

<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>

and the code behind for that user control:

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;
        }
    }
}

so on my main window I will be able to use that user control by:

1) importing the namespace where that user control is:

  xmlns:myCtrl ="clr-namespace:PDV.UserControls"

2) placing that control in that window:

  <myCtrl:InputField LblContent="hello" Margin="0,0,483,0" Height="49" VerticalAlignment="Top"></myCtrl:InputField>

What do I have to do so that when I update LblContent="hello" it renders on the window? It will be nice for it to render at design time not just at runtime

I think that the second type of might be InputField public static DependencyProperty MessageProperty = DependencyProperty.Register( "LblContent", typeof(string), typeof(InputField));

I never try to set the DataContext in your way, eventually try to give a name at the usercontrol x:Name="Root" then change the binding like this: Content="{Binding Path=LblContent, ElementName=Root}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM