显然,在WinUI 3中尚不支持Setter中的通用绑定,尽管这是一个备受请求的功能。一种解决方法是创建一个带有DependencyProperty的辅助类,每当属性被更改/设置时调用更改处理程序。然后,更改处理程序可以在代码中创建所需的绑定。感谢clemens很久以前为UWP建议了这样的东西。以下是一个示例辅助类:
internal class BindingHelper
{
#region CompactPaneLengthBindingPath
public static readonly DependencyProperty CompactPaneLengthBindingPathProperty = DependencyProperty.RegisterAttached(
"CompactPaneLengthBindingPath", typeof(string), typeof(BindingHelper), new PropertyMetadata(null, BindingPathChanged));
public static string GetCompactPaneLengthBindingPath(DependencyObject obj)
{
return (string)obj.GetValue(CompactPaneLengthBindingPathProperty);
}
public static void SetCompactPaneLengthBindingPath(DependencyObject obj, string value)
{
obj.SetValue(CompactPaneLengthBindingPathProperty, value);
}
#endregion
#region HeightBindingPath
#region ForegroundBindingPath
private static void BindingPathChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is string source)
{
DependencyProperty target;
if (e.Property == CompactPaneLengthBindingPathProperty) target = NavigationView.CompactPaneLengthProperty;
else if (e.Property == HeightBindingPathProperty) target = FrameworkElement.HeightProperty;
else if (e.Property == ForegroundBindingPathProperty) target = Control.ForegroundProperty;
else throw new System.Exception($"BindingHelper: Unknown target ({nameof(e.Property)}");
obj.ClearValue(target);
BindingOperations.SetBinding(obj, target,
new Binding { Path = new PropertyPath(source), Mode = BindingMode.OneWay });
}
}
请注意,所有的DependencyProperties都是字符串类型,并且目标类型可以是您正在使用的控件的任何祖先类型。例如,HeightBindingPathProperty绑定可以与任何FrameworkElement一起使用。
在样式中使用助手与使用任何Setter一样,如下所示:
<Style x:Key="MyNavigationView" TargetType="controls:NavigationView" >
<Setter Property="local:BindingHelper.CompactPaneLengthBindingPath" Value="CurrentCompactPaneLength" />
</Style>
希望这能有所帮助。