Reputation: 421
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?
Upvotes: 2
Views: 4368
Reputation: 385
my answer may too late for this issue, but i see many people still involved with this common problem,you can do it with datatriggers
<Label>
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding BoolCondition}" Value="true">
<Setter Property="Text" Value="Orange" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding BoolCondition}" Value="false">
<Setter Property="Text" Value="Red" />
</DataTrigger>
</Label.Triggers>
</Label>
Upvotes: 3
Reputation: 600
I think you could achieve this goal by setting binding property in code-behind (xaml.cs
file) instead of .xaml
file.
For example:
MainPage.xaml
, you have a label with name labelA
: <Label x:Name="labelA" />
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));
}
}
Upvotes: 3