/// <summary> /// Gets the data property binding from a dependency object or its parent. /// </summary> /// <param name="obj">Dependency object.</param> /// <returns>Data property binding or null if not found.</returns> private static DataPropertyBinding GetBinding(DependencyObject obj) { if (obj == null) { return(null); } DataPropertyBinding b = obj.GetValue(Property.BindingProperty) as DataPropertyBinding; return(b); }
/// <summary> /// A handler of the data context change event on a text block that has a value format dependency property set, /// which updates the text of the text block to be formatted according to the specified value format. /// </summary> /// <param name="sender">Event sender, which should be a text block.</param> /// <param name="e">Event arguments.</param> private static void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (!(sender is TextBlock tb)) { return; } DataPropertyBinding binding = GetBinding(tb); if (binding != null && binding.BoundProperty != null) { tb.Text = binding.BoundProperty.ValueToString(tb.DataContext, GetValueFormat(tb)); } }
/// <summary> /// A callback that is triggered when a data property name or a child object path /// are set on a framework element. It sets up a new data property binding on the element. /// </summary> /// <param name="d">The framework element.</param> /// <param name="e">Event arguments.</param> public static void SetupBinding(DependencyObject d, DependencyPropertyChangedEventArgs e) { // calling a static method IsBindable ensures that // the static constructor is called and all WPF bindings get registered if (DataPropertyBinding.IsBindable(d)) { BaseBinding oldBinding = d.GetValue(BindingProperty) as BaseBinding; if (oldBinding != null) { oldBinding.Dispose(); } d.SetValue(BindingProperty, BaseBinding.Create(d)); } }