I have a Page
called HomePage
in a WinUI 3 Desktop App. HomePage
has two DependencyProperties
, P1
and P2
. I would like to create a binding that uses P1
as the source and P2
as the target (assume P1
and P2
are of the same type). This can be done easily in code but, can I create the binding in XAML?
This is the code for the binding:
public sealed partial class HomePage : Page
{
public HomePage()
{
InitializeComponent();
// Dependency property identifiers are static public fields. This is the identifier of the Target.
var targetInfo = typeof(HomePage).GetField("P2Property", BindingFlags.Static | BindingFlags.Public);
if (targetInfo is not null && targetInfo.FieldType == typeof(DependencyProperty))
{
Binding bBinding = new() { Path = new PropertyPath("P1"), Source=this, Mode = BindingMode.OneWay };
// this is a static field (there are no instance versions) and the value is the identifier of the DependencyProperty
var dp = (DependencyProperty)targetInfo.GetValue(null);
ClearValue(dp);
SetBinding(dp, bBinding); // create the binding
}
}
// P1
public static readonly DependencyProperty P1Property = DependencyProperty.Register(
"P1", typeof(object), typeof(HomePage), new PropertyMetadata(null));
public object P1
{
get => (object)GetValue(P1Property);
set => SetValue(P1Property, value);
}
// P2
public static readonly DependencyProperty P2Property = DependencyProperty.Register(
"P2", typeof(object), typeof(HomePage), new PropertyMetadata(null));
public object P2
{
get => (object)GetValue(P2Property);
set => SetValue(P2Property, value);
}
}
Can the binding (bBinding
) be created in XAML instead?
[Edit] Thank you for the answers, which I have tried, but issues remain. Here is the XAML for HomePage:
<Page
x:Class="PFSI.Views.HomePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:PFSI.Views"
x:Name="homePage">
<Grid>
<!-- Blah -->
</Grid>
</Page>
Defining the binding isn't the issue - any of: P2="{Binding P1, ElementName=homePage}"
; P2="{Binding RelativeSource={RelativeSource Self}, Path=P1}"
;
or P2="{x:Bind P1, Mode=OneWay}"
should work provided they can be applied to an element. DataContext
is set to the HomeViewModel
but that shouldn't matter here.
I tried using the suggested <views:HomePage ... />
but the result is a stack overflow as the the compiler loops from the element to the class and back.
I thought a Style
might work (something like:
<Setter Property="P2" Value="{Binding RelativeSource={RelativeSource Self}, Path=P1}"/>
) but Setters
in WinUI 3 Styles
don't support bindings (although, curiously, bindings work in VisualStateManager
Setters
).
I'm sure this should work in XAML - maybe it just needs to wait for Setter
Binding
support?