Created
June 7, 2024 09:32
-
-
Save BYJRK/1220906e7c4b6cb863ec6d204abcb2a6 to your computer and use it in GitHub Desktop.
Change the value of an attached property of a target object with Interaction.Triggers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Xaml.Behaviors; | |
using System.ComponentModel; | |
using System.Reflection; | |
using System.Windows; | |
public class ChangeAttachedPropertyAction : TargetedTriggerAction<UIElement> | |
{ | |
public Type? ClassType | |
{ | |
get { return (Type)GetValue(ClassTypeProperty); } | |
set { SetValue(ClassTypeProperty, value); } | |
} | |
public static readonly DependencyProperty ClassTypeProperty = DependencyProperty.Register( | |
nameof(ClassType), | |
typeof(Type), | |
typeof(ChangeAttachedPropertyAction), | |
new PropertyMetadata(null) | |
); | |
public string? PropertyName | |
{ | |
get => (string)GetValue(PropertyNameProperty); | |
set => SetValue(PropertyNameProperty, value); | |
} | |
public static readonly DependencyProperty PropertyNameProperty = DependencyProperty.Register( | |
nameof(PropertyName), | |
typeof(string), | |
typeof(ChangeAttachedPropertyAction), | |
new PropertyMetadata("") | |
); | |
public object? Value | |
{ | |
get => GetValue(ValueProperty); | |
set => SetValue(ValueProperty, value); | |
} | |
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( | |
nameof(Value), | |
typeof(object), | |
typeof(ChangeAttachedPropertyAction), | |
new PropertyMetadata(null) | |
); | |
protected override void Invoke(object parameter) | |
{ | |
ArgumentNullException.ThrowIfNull(ClassType, nameof(ClassType)); | |
ArgumentException.ThrowIfNullOrEmpty(PropertyName, nameof(PropertyName)); | |
MethodInfo setter = ClassType.GetMethod($"Set{PropertyName}", BindingFlags.Static | BindingFlags.Public) ?? throw new ArgumentException($"Method Set{PropertyName} not found in {ClassType}"); | |
var tc = TypeDescriptor.GetConverter(setter.GetParameters()[1].ParameterType); | |
if (Value != null && tc.CanConvertFrom(Value.GetType())) | |
{ | |
setter.Invoke(null, [Target, tc.ConvertFrom(Value)]); | |
} | |
else | |
{ | |
setter.Invoke(null, [Target, Value]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment