On my WPF XAML form I’ve got a lot of elements which I bind to my properties.
For each one property I’m making this 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 realize for now how many times I will need to write the same here but I don’t know if I can make it somehow easier? Because all I need to set from here is WPF block name and binding name.
There are a couple of ways you can reduce repetition:
ItemsControlwith anItemTemplateto create the repeated elements.I have spotted a few issues with your code:
OnCaptionPropertyChangedmethod you set theTextBlock.Text, you should noty do this – this binding will take care of the update!TBX11property you invoke this methodOnPropertyChanged("TBX11"), you should not add any logic to the getters or setters of dependency properties. There is no guarantee these will be invoked.TextBlock.DataContextis set to itself, so theTextbinding will not work!