XAML-Map-Control/MapControl/Avalonia/DependencyPropertyHelper.Avalonia.cs

66 lines
2.3 KiB
C#
Raw Normal View History

2024-05-24 09:13:41 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// Copyright © 2024 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
2024-05-20 23:24:34 +02:00
using Avalonia.Controls;
using System;
2024-05-21 14:39:53 +02:00
#pragma warning disable AVP1001 // The same AvaloniaProperty should not be registered twice
2024-05-20 23:24:34 +02:00
namespace MapControl
{
public static class DependencyPropertyHelper
{
2024-05-21 13:51:10 +02:00
public static StyledProperty<TValue> Register<TOwner, TValue>(
2024-05-20 23:24:34 +02:00
string name,
TValue defaultValue = default,
2024-05-21 13:51:10 +02:00
Action<TOwner, TValue, TValue> changed = null,
2024-05-23 18:22:52 +02:00
Func<TOwner, TValue, TValue> coerce = null,
bool bindTwoWayByDefault = false)
2024-05-20 23:24:34 +02:00
where TOwner : AvaloniaObject
{
Func<AvaloniaObject, TValue, TValue> coerceFunc = null;
if (coerce != null)
{
// do not coerce default value
coerceFunc = (obj, value) => value.Equals(defaultValue) ? value : coerce((TOwner)obj, value);
}
var bindingMode = bindTwoWayByDefault ? Avalonia.Data.BindingMode.TwoWay : Avalonia.Data.BindingMode.OneWay;
var property = AvaloniaProperty.Register<TOwner, TValue>(name, defaultValue, false, bindingMode, null, coerceFunc);
2024-05-20 23:24:34 +02:00
2024-05-21 13:51:10 +02:00
if (changed != null)
2024-05-20 23:24:34 +02:00
{
2024-05-21 13:51:10 +02:00
property.Changed.AddClassHandler<TOwner, TValue>((o, e) => changed(o, e.OldValue.Value, e.NewValue.Value));
2024-05-20 23:24:34 +02:00
}
return property;
}
2024-05-21 13:51:10 +02:00
public static AttachedProperty<TValue> RegisterAttached<TOwner, TValue>(
2024-05-20 23:24:34 +02:00
string name,
TValue defaultValue = default,
2024-05-23 19:21:28 +02:00
Action<Control, TValue, TValue> changed = null,
bool inherits = false)
2024-05-20 23:24:34 +02:00
{
2024-05-21 13:51:10 +02:00
var property = AvaloniaProperty.RegisterAttached<TOwner, Control, TValue>(name, defaultValue, inherits);
2024-05-20 23:24:34 +02:00
2024-05-21 13:51:10 +02:00
if (changed != null)
2024-05-20 23:24:34 +02:00
{
2024-05-21 13:51:10 +02:00
property.Changed.AddClassHandler<Control, TValue>((o, e) => changed(o, e.OldValue.Value, e.NewValue.Value));
2024-05-20 23:24:34 +02:00
}
return property;
}
2024-05-24 15:14:05 +02:00
public static StyledProperty<TValue> AddOwner<TOwner, TValue>(
StyledProperty<TValue> property)
where TOwner : AvaloniaObject
{
return property.AddOwner<TOwner>();
}
2024-05-20 23:24:34 +02:00
}
}