XAML-Map-Control/MapControl/Shared/BindingHelper.cs

52 lines
2.1 KiB
C#
Raw Normal View History

2021-06-14 21:41:37 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2024-02-03 21:01:53 +01:00
// Copyright © 2024 Clemens Fischer
2021-01-17 23:39:20 +01:00
// Licensed under the Microsoft Public License (Ms-PL)
2021-06-14 21:41:37 +02:00
#if WINUI
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Data;
2021-11-17 23:17:11 +01:00
#elif UWP
2021-01-17 23:39:20 +01:00
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#else
using System.Windows;
using System.Windows.Data;
#endif
namespace MapControl
{
2021-06-14 21:41:37 +02:00
internal static class BindingHelper
2021-01-17 23:39:20 +01:00
{
2021-12-01 20:15:48 +01:00
/// <summary>
/// Returns a Binding to the specified dependency property of a FrameworkElement.
/// If the source property is itself already bound, the method returns the existing Binding,
/// otherwise it creates one with sourceElement as Source and sourcePropertyName as Path.
/// </summary>
public static Binding GetOrCreateBinding(
this FrameworkElement sourceElement, DependencyProperty sourceProperty, string sourcePropertyName)
2021-01-17 23:39:20 +01:00
{
2021-12-01 20:15:48 +01:00
var sourceBinding = sourceElement.GetBindingExpression(sourceProperty);
return sourceBinding != null
? sourceBinding.ParentBinding
: new Binding { Source = sourceElement, Path = new PropertyPath(sourcePropertyName) };
2021-01-17 23:39:20 +01:00
}
2021-12-01 20:15:48 +01:00
/// <summary>
/// Sets a Binding on the specified dependency property of targetElement, if the target property does
/// not yet have a value or a Binding assigned to it. The potentially assigned Binding is created by
/// GetOrCreateBinding(sourceElement, sourceProperty, sourcePropertyName).
/// </summary>
public static void SetBindingOnUnsetProperty(
this FrameworkElement targetElement, DependencyProperty targetProperty,
FrameworkElement sourceElement, DependencyProperty sourceProperty, string sourcePropertyName)
2021-01-17 23:39:20 +01:00
{
2021-12-01 20:15:48 +01:00
if (targetElement.GetValue(targetProperty) == null &&
targetElement.GetBindingExpression(targetProperty) == null)
2021-01-17 23:39:20 +01:00
{
2021-12-01 20:15:48 +01:00
targetElement.SetBinding(targetProperty, GetOrCreateBinding(sourceElement, sourceProperty, sourcePropertyName));
2021-01-17 23:39:20 +01:00
}
}
}
}