How can I use an ObservableObject (from Community Toolkit) as a Binding Target in code and XAML in a WinUI 3 Desktop app?
Here's a simple (partial) homepage example:
<!-- Home.xaml -->
<Page
x:Class="PFSI.Views.Home"
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:vms="using:PFSI.ViewModels"
mc:Ignorable="d" >
<Page.DataContext>
<vms:HomeViewModel x:Name="ViewModel" />
</Page.DataContext>
<Grid x:Name="ContentArea" >
<TextBlock x:Name="TBox" Text="This text should be shaded." Foreground="{Binding Shade}" />
</Grid>
</Page>
// Home.xaml.cs
public partial class HomePage : Page
{
public HomePage()
{
InitializeComponent();
}
}
// HomeViewModel.cs
public class HomeViewModel : ObservableObject
{
public HomeViewModel()
{
Classes.TraceListener.TraceMessage(GetType().Name);
}
[ObservableProperty]
private SolidColorBrush shade;
}
Using the property Shade as a source is straightforward in XAML (see the TextBlock in Home.xaml) or in code:
Binding bBinding = new() { Path = new PropertyPath("Shade"), Source = ViewModel, Mode = BindingMode.OneWay };
TBox.SetBinding(TextBox.ForegroundProperty, bBinding);
But what if I want to make the property Shade the target of the binding (that is, I want to set Shade with the binding)?
BindingOperations.SetBinding(DependencyObject target, DependencyProperty dp, BindingBase binding)
requires a DependencyObject
(which HomeViewModel is not, it's an ObservableObject) and a DependencyProperty identifier (which Shade doesn't have as it's
a normal property).
I'm sure this is possible but I'm at a loss for the moment. Any help most welcome.