My attempt to create a CustomControl like a TextBox with variable caption.
I try to learn create CustomControl and my exceptation is that my CustomControl (I called it TextBoxCustomControl) has every properties and methods of TextBox and also has new property Caption.
I hope that is right, that my TextBoxCustomControl is inherited from TextBox and not from Control.
TextBoxCustomControl.cs
namespace CustomControlProject
{
public class TextBoxCustomControl : TextBox
{
public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(TextBoxCustomControl), new FrameworkPropertyMetadata(String.Empty));
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
static TextBoxCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxCustomControl), new FrameworkPropertyMetadata(typeof(TextBoxCustomControl)));
}
}
}
Themes\Generic.xaml (specific design for TextBoxCustomControl) -- there is the TextBox called innerTextBox
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlProject">
<Style x:Name="CustomStyle" TargetType="local:TextBoxCustomControl" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TextBoxCustomControl}">
<WrapPanel Orientation="Vertical">
<TextBox x:Name="innerTextBox" />
<Label Content="{TemplateBinding Caption}" />
</WrapPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
In MainWindow.xaml I use my TextBoxCustomControl and specific some properties for it.
<Window x:Class="CustomControlProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlProject"
Title="MainWindow" Height="350" Width="525">
<WrapPanel>
<local:TextBoxCustomControl Width="287" Background="Yellow" Caption="Fill the nickname, please." />
</WrapPanel>
</Window>
My expectation is that innerTextBox inside my TextBoxCustomControl inherit all properties (such like background, width, etc.), but that is not happened. What I do wrong?