Home > Net >  RelayCommand in MVVM community toolkit does not respond to the observable property in WPF
RelayCommand in MVVM community toolkit does not respond to the observable property in WPF

Time:10-15

I'm using ObservableProperty attribute from MVVM toolkit, for the string SearchString which has binding for the TextBlock.Text property. I want to start command once change in TextBlock was made so I have set the attribute for change notification.

ViewModel part:

    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(UpdateSearchCommand))]
    string searchString = string.Empty;

    [RelayCommand]
    async Task UpdateSearch()
    {
        MessageBox.Show("Hello");
        await Task.CompletedTask;
    }

View part:

       <TextBox x:Name="txtSearch" Width="200" Height="30"
          Grid.Row="0" Grid.Column="0"
          HorizontalAlignment="Right"
          VerticalAlignment="Center"
             BorderThickness="0"
             Margin="0 0 10 0"
             Padding="0 5 0 0"
             Text="{Binding SearchString}">
       <TextBox.ToolTip>
          <ToolTip Content="{Binding Loc[SearchNameOrDesc_TT]}"/>
       </TextBox.ToolTip>

I don't know why, but when I write something into textBlock, the command does not trigger.

Does anybody has some experience with such as behavior?

I'll be glad for any advice or even a hint.

Thanks

CodePudding user response:

You didn't bind your Command to your View. First of all, you need to understand how the binding works.

You didn't bind your Command to anything. Instead, you're only notifying the View to update any bindings to the Command, which is not doing anything here, because it's not bound to anything.

If you want to invoke the Command through the binding of the SearchString property, you'll need to update your code as follows:

[ObservableProperty]
string searchString;

partial void OnSearchStringChanged(string value)
{
    UpdateSearchCommand.Execute(null); //or pass value, if you need to 
}

[RelayCommand]
void UpdateSearch()
{
    MessageBox.Show("Hello");
}

Note: This is not an ideal implementation, just a way to fix your code based on how I understood it.

You should probably familiarize yourself more with property bindings and commands before using advanced things like MVVM Code Generators.

  • Related