Search code examples
mvvmdata-bindingmauicommunity-toolkit-mvvm

How to do binding based on a condition in .net maui?


I'd like to ask how to do the conditional binding in a .net Maui app. for example

if I have a class

public class ClassA
{
     public string Property1{get;set;}
     public string Property2{get;set;}
}

and I don't have access to the class implementation so I cannot add methods

and in my view, I want to bind to Property1 if some condition is true and bind to Property2 if that condition was false.

Is there a way to do conditional binding from the view itself without changing ClassA implementation?


Solution

  • I think you could achieve this goal by setting binding property in code-behind (xaml.cs file) instead of .xaml file.

    For example:

    • In MainPage.xaml, you have a label with name labelA:
      <Label x:Name="labelA" />
    
    • In MainPage.xaml.cs constructor, you could bind Text property of labelA to one of viewModel properties based on a condition.
    public MainPage(ClassA viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    
        if (true condition)
        {
            labelA.SetBinding(Label.TextProperty, nameof(viewModel.Property1));
        }
        else
        {
            labelA.SetBinding(Label.TextProperty, nameof(viewModel.Property2));
        }
    }