0

My goal is essentially to have two separate classes, a searchbox and textfield, react to one another once their counterparts' values change.

I've been experimenting with the new MVVM toolkit of Microsoft, and I've explored the [ObservableProperty] command and [RelayCommand] annotations. However, one issue I am having is their documentation, which needs more details. This is why I am trying this place, to see if someone could shed some light on my implementation.

We have Searchbox.cs that happens to be an ObservableObject, and its automagical function OnTextChange automatically triggers once its value changes. That's good.

// Searchbox.cs

    public partial class Searchbox : ObservableObject
    {
        [ObservableProperty]
        private string text;

        partial void OnTextChanged(string value)
        {

            // notify Textfield about change
            //
            // Textfield.onChange(doSomething => {
            //      OnSearchboxTextChange();
            // });
            //

            Console.WriteLine("Something changed for Text!");
        }
    }

However, somewhere else in my app, totally separate from Searchbox is Textfield.cs and I also want it to react to OnTextChange. I made a function for it OnSearchboxTextChange. Now, my first implementation was just exposing Textfield and calling OnSearchboxTextChange via [RelayCommand] in the Textfield.cs class, but I thought that was not an elegant solution, since I'm exposing textfield right away.

// Textfield.cs

    public class Textfield
    {
        public void OnSearchboxTextChange()
        {
            // react to Searchbox value changing
        }
    }

I tried looking at the annotation [NotifyPropertyChangeRecipients] but the document is definitely unclear on its implementation. Any tips?

1 Answers1

0

You are likely looking for a messenger. The CommunityToolkit already contains one that you can use:

https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/messenger

somebody
  • 89
  • 1
  • 4