Data binding through UserControl

18 Views Asked by At

Here's a minimal example of data binding. I would like know how to factor out both the ToggleSwitch and Button into different UserControls while keeping the data binding.

//MainWindow.xaml
<StackPanel>
    <ToggleSwitch x:Name="MyToggle" OffContent="Off" OnContent="On"/>
    <Button IsEnabled="{x:Bind MyToggle.IsOn, Mode=OneWay}" Content="Click Me"/>
</StackPanel>

// MainWindow.idl
Microsoft.UI.Xaml.Controls.ToggleSwitch MyToggle{ get; };
1

There are 1 best solutions below

0
Tom Huntington On BEST ANSWER

Publically expose MyToggleControl and MyToggle so "{x:Bind MyToggleControl.MyToggle.IsOn}" is available. Then create IsButtonEnabled property so that IsButtonEnabled="{x:Bind ...}" will work.


Expose the UserControlToggle as a public property of MainWindow

// MainWindow.xaml
<StackPanel>
    <local:UserControlToggle x:Name="MyToggleControl" x:FieldModifier="public"/>
    <local:UserControlButton IsButtonEnabled="{x:Bind MyToggleControl.MyToggle.IsOn, Mode=OneWay}"/>
</StackPanel>

// MainWindow.idl needed for cppwinrt as x:FieldModifier doesn't work
import "UserControlToggle.idl";
UserControlToggle MyToggleControl{ get; };

Expose the ToggleSwitch as a public property of UserControlToggle

// UserControlToggle.xaml
<ToggleSwitch x:Name="MyToggle" x:FieldModifier="public" OffContent="Off" OnContent="On"/>

// UserControlToggle.idl
Microsoft.UI.Xaml.Controls.ToggleSwitch MyToggle{ get; };

Wrap the buttons IsEnabled property to a property on UserControlButton

// UserControlButton.xaml
<Button x:Name="myButton" Click="myButton_Click">Enable/Disable</Button>

// UserControlButton.idl
Boolean IsButtonEnabled;

// UserControlButton.xaml.cpp
bool UserControl::IsButtonEnabled()
{
    return myButton().IsEnabled();
}

void UserControl::IsButtonEnabled(bool value)
{
    myButton().IsEnabled(value);
}