microsoft / XamlBehaviors

This is the official home for UWP XAML Behaviors on GitHub.
MIT License
697 stars 112 forks source link

Binding to Window Activated or Loaded event in WinUI 3 #193

Open icnocop opened 4 years ago

icnocop commented 4 years ago

Hi.

I'm trying to bind the Window Activated and Loaded events in a WinUI 3 desktop application to an ICommand property in my ViewModel, but running into issues.

I've attached a sample app here: BindingLoadedEvent.zip

Visual Studio 2019 16.7.1 .NET v5.0.100-preview.7 WinUI 3.0.0-preview2.200713.0 Microsoft.Xaml.Behaviors.WinUI.Managed 2.0.3-rc3 Microsoft.Toolkit.Mvvm 7.0.0-preview2

With the sample code, I'm currently getting XamlParseException: 'XAML parsing failed.'.

MainWindow.xaml

<Window
    x:Name="MyMainWindow">
    <i:Interaction.Behaviors>
        <ic:EventTriggerBehavior SourceObject="{x:Bind MyMainWindow}" EventName="Activated">
            <ic:EventTriggerBehavior.Actions>
                <ic:InvokeCommandAction Command="{x:Bind ViewModel.ActivatedCommand}"/>
            </ic:EventTriggerBehavior.Actions>
        </ic:EventTriggerBehavior>
    </i:Interaction.Behaviors>

MainWindow.xaml.cs

public MainViewModel ViewModel { get; } = (App.Current as App).Container.GetService<MainViewModel>();

MainViewModel.cs

public class MainViewModel
{
    public MainViewModel()
    {
        this.ActivatedCommand = new AsyncRelayCommand(
            this.Activated);
    }

    public IAsyncRelayCommand ActivatedCommand { get; }

    public async Task Activated()
    {
        await Task.Run(() =>
        {
            // not called
        });
    }
}

Any ideas?

Thank you.

Noemata commented 3 years ago

@icnocop , Look at the code here: https://github.com/Noemata/SimpleMVVM

For a howto example.