How to create a template for WPF properties?

In my WPF XAML form, I have many elements that I bind to my properties.

For each property, I do the following steps:

<TextBlock Grid.Column="0" Grid.Row="0" Name="TB11" Text="{Binding TBX11}" 
            VerticalAlignment="Center" HorizontalAlignment="Center" 
            DataContext="{Binding RelativeSource={RelativeSource Self}}" />

and

#region TBX11
private static void OnXBPropertyChanged(DependencyObject dependencyObject,
                DependencyPropertyChangedEventArgs e) 
{
    table myUserControl = dependencyObject as table;
    myUserControl.OnPropertyChanged("XB11");
    myUserControl.OnCaptionPropertyChanged(e);
}
private void OnCaptionPropertyChanged(DependencyPropertyChangedEventArgs e) {
    TB11.Text = TBX11;
}
public static readonly DependencyProperty TBX11Property =
        DependencyProperty.Register("TBX11", typeof(string), typeof(table),
        new PropertyMetadata(string.Empty, OnXBPropertyChanged));
public string TBX11 {
    get { return GetValue(TBX11Property).ToString(); }
    set {
        SetValue(TBX11Property, value);
        OnPropertyChanged("TBX11");
    }
}
#endregion

I can’t even understand how many times I will need to write the same thing here, but I don’t know if I can make it any easier? Because all I need to install here is the name of the WPF block and the name of the binding.

+3
source share
2 answers

There are several ways to reduce recurrence:

:

  • OnCaptionPropertyChanged TextBlock.Text, - !
  • TBX11 OnPropertyChanged("TBX11"), - . , .
  • TextBlock.DataContext , Text !
+2

, - ?

MVVM, Caliburn Micro.

Caliburn lets you rewrite your XAML as

 <TextBlock Grid.Column="0" Grid.Row="0" Name="TB11"  
        VerticalAlignment="Center" HorizontalAlignment="Center"/> 
+1
source

All Articles