Search code examples
c#winui-3xbind

C# replace Binding with x:Bind (Migrate UWP to WinUI 3)


I have a Page.Resources Datatemplate, there I specify an x:DataType

     <Page.Resources>
         <DataTemplate x:Key="DataPanelTemplate" x:DataType="dataModel:Activity">
    

the problem is in this DataTemplate I have this AppBarButton:

      <AppBarButton Icon="Stop" IsCompact="True" x:Name="cmdStopActivity" >
                    <Interactivity:Interaction.Behaviors>
                        <Core:EventTriggerBehavior EventName="Click">
                            <Core:InvokeCommandAction Command="{Binding ActivitiesViewModel.FinishActivityCommand, Source={StaticResource Locator}}" 
                                                      CommandParameter="{Binding}"/>
                        </Core:EventTriggerBehavior>
                    </Interactivity:Interaction.Behaviors>
                </AppBarButton>
  

How can I define the InvokeCommandAction Command as x:Bind? There I need access to the ViewModel and not to the specified x:DataType. I tryed this:

     xmlns:viewModel="using:PnxZeiterfassung.ViewModel"
     x:Bind viewModel:ActivitiesViewModel.FinishActivityCommand
      public RelayCommand<Activity> FinishActivityCommand { get; set; }
      FinishActivityCommand = new RelayCommand<Activity>(async (a) => await FinishActivity(a));

but here the FinishActivityCommand is not recognized.


Solution

  • In a DataTemplate, you can only use x:Bind to bind to a property of the the type specified by the x:DataType attribute.

    You cannot x:Bind to a view model property from inside a DataTemplate so, in this case, it's not possible or supported to use x:Bind to bind the CommandParameter property to a property of the view model. You should stick with the {Binding} markup.