We should have our work get easier, shouldn’t we?
So I don’t like to repeat label + text box all over, that duet is a good choose for user control, and so it is:
(and keep remember, I’m still learning..)
PlainTextBox.xaml:
<UserControl x:Class="PlainTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="me"
Style="{StaticResource MyControlStyle}">
<UserControl.Resources>
<ResourceDictionary>
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</UserControl.Resources>
<StackPanel>
<Label Target="{Binding ElementName=txtBox}" Content="{Binding Path=Caption, ElementName=me}" />
<TextBox x:Name="txtBox"/>
</StackPanel>
</UserControl>
PlainTextBox.xaml.cs
public partial class PlainTextBox : UserControl
{
// Using a DependencyProperty as the backing store for Caption. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Caption", typeof(string), typeof(PlainTextBox), new UIPropertyMetadata(""));
// Using a DependencyProperty as the backing store for Path. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PathProperty =
DependencyProperty.Register("PathName",
typeof(string),
typeof(PlainTextBox),
new PropertyMetadata("", MyPathChanged));
public PlainTextBox()
{
InitializeComponent();
}
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
public string PathName
{
get { return (string)GetValue(PathProperty); }
set { SetValue(PathProperty, value); }
}
private static void MyPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PlainTextBox tc = d as PlainTextBox;
Binding myBinding = new Binding("MyDataProperty");
myBinding.Mode = BindingMode.TwoWay;
myBinding.Path = new PropertyPath(tc.PathName);
myBinding.ValidatesOnDataErrors = true;
myBinding.ValidatesOnExceptions = true;
tc.txtBox.SetBinding(TextBox.TextProperty, myBinding);
}
}
And usage:
<ctr:PlainTextBox Caption="Last name" PathName="DetailData.LastName"></ctr:PlainTextBox>
And that way all data binding attributes are encapsulated in user control, so I do not need repeat that I want validation on errors all over in my code.
Advertisement