Search code examples
data-bindingwinui-3windows-community-toolkit

Relay Command doesn't execute


I've decided to use the mvvm architecture in my project and tried converting my code to it. But it looks like I'm misunderstanding something, as the properties I'd like to set in an relay command are either not changed or the changing has no effect. Either way this behavior is not desired.

My code is very simple and looks like this:

MainViewModel.cs

public partial class MainViewModel : ObservableRecipient
{
    [ObservableProperty] private string testText;

    [RelayCommand]
    private void Toggle()
    {
        testText = "pressed";
    }
}

Mainview.xaml

<Page
    x:Class="Calendarium.Views.MainPage"
    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"
    mc:Ignorable="d"
    xmlns:viewModels="using:Calendarium.ViewModels"
    d:DataContext="{d:DesignInstance Type=viewModels:MainViewModel}">
    <Grid>
         <TextBlock Text="{Binding TestText}">
         <Button Command="{Binding ToggleCommand}">
    </Grid>
</Page>

Solution

  • You seem to have set the design time DataContext only.

    You also need to set the actual DataContext that is used at runtime:

    <Page
        x:Class="Calendarium.Views.MainPage"
        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"
        mc:Ignorable="d"
        xmlns:viewModels="using:Calendarium.ViewModels"
        d:DataContext="{d:DesignInstance Type=viewModels:MainViewModel}">
        <Page.DataContext>
            <viewModels:MainViewModel />
        </Page.DataContext>
        <Grid>
            ...
        </Grid>
    </Page>
    

    Besides, you should set the value of the generated property in your Toggle method:

    [RelayCommand]
    private void Toggle()
    {
        TestText = "pressed";
    }