可以绑定到目标对象,然后指定要设置的源属性。无论何时设置了任何目标属性,都应尝试设置源属性。试试这个:
public class RoutePropertyValue : Behavior<FrameworkElement>
{
public object Source
{
get => GetValue(SourceProperty);
set => SetValue(SourceProperty, value);
}
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(nameof(Source), typeof(object),
typeof(RoutePropertyValue), new PropertyMetadata(null, Callback));
private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is RoutePropertyValue instance)
instance.OnAnyValueChanged();
}
protected virtual void OnAnyValueChanged()
{
if (!string.IsNullOrEmpty(TargetMember))
TargetObject?.GetType().GetProperty(TargetMember)?.SetValue(TargetObject, Source);
}
public object TargetObject
{
get => GetValue(TargetObjectProperty);
set => SetValue(TargetObjectProperty, value);
}
public static readonly DependencyProperty TargetObjectProperty = DependencyProperty.Register(nameof(TargetObject), typeof(object),
typeof(RoutePropertyValue), new PropertyMetadata(null, Callback));
public string TargetMember
{
get => (string)GetValue(TargetMemberProperty);
set => SetValue(TargetMemberProperty, value);
}
public static readonly DependencyProperty TargetMemberProperty = DependencyProperty.Register(nameof(TargetMember), typeof(string),
typeof(RoutePropertyValue), new PropertyMetadata(null, Callback));
}
xaml:
<behaviors:RoutePropertyValue
TargetObject="{Binding}"
TargetMember="Index"
Source="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=(ItemsControl.AlternationIndex)}"
/>