2

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?

Julian
  • 5,290
  • 1
  • 17
  • 40
Shehab
  • 431
  • 2
  • 10
  • Can you explain the purpose of this? What is your goal? Please show what you're actually trying, e.g. provide some XAML to explain how and why you would like to have a conditional binding. AFAIK you cannot change the binding source based on a condition purely in XAML during runtime. However, your problem may be solved in a different way if you provide more context. – Julian Nov 26 '22 at 10:50
  • 1
    Create a ViewModel that implements any custom logic required for your UI – Jason Nov 26 '22 at 11:59

1 Answers1

2

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));
    }
}
Hoàng Trần
  • 549
  • 6
  • 14