Attach the usercontrol property and update it at design time
How do I create a custom control like a textbox? For example, when I change the Text property of a Textbox control, new text appears in the window I'm currently working in.
In my project I have many places where the user has to enter information, so I want to create a custom InputField control. (that usercontrol consists of a custom styled textbox label)
Here is the xaml for my custom 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 for this custom 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 in my main window I will be able to use this user control:
1) importing the namespace that this custom control resides in:
xmlns:myCtrl ="clr-namespace:PDV.UserControls"
2) placing this control in this window:
<myCtrl:InputField LblContent="hello" Margin="0,0,483,0" Height="49" VerticalAlignment="Top"></myCtrl:InputField>
What do I need to do to make LblContent="hello"
it appear in the window when updated ? This will be useful for design-time rendering not only at runtime
source to share
I think the second type could be InputField public static DependencyProperty MessageProperty = DependencyProperty.Register ("LblContent", typeof (string), typeof (InputField));
I never try to set the DataContext in your path, eventually try to give a name in usercontrol x: Name = "Root" and then change the binding like this: Content = "{Binding Path = LblContent, ElementName = Root}"
source to share