Let's say I have ControlA
, where in code-behind I have some property PropertyA
, that are instance properties for bindable properties. I want to channel their values to PropertyB
in control ControlB
that is declared in XAML.
Now I can bind to property like so:
<ContentView
...
x:Name="Self">
<ContentView.Content>
<ControlB
x:Name="ConB"
PropertyB="{Binding Source={x:Reference Self}, Path=PropertyA}/>
</ContentView.Content>
</ContentView>
Or in the code behind like so:
protected override void OnPropertyChanged(string propertyName = null)
{
if(propertyName == nameof(PropertyA)
{
ConB.PropertyB = PropertyA;
}
}
Is one of the approaches better than the other?
CodePudding user response:
I prefer the first case.
REASON: Put code where it applies, not in a centralized place requiring
if ... elseif ...
That gets messy.
And if you are looking at XAML
for ControlB
, there is no indication that you also need to go look in cs
file, OnPropertyChanged
method, to understand what affects it.
The only time I would consider it, is if it was an expression that was difficult to write in XAML
. For example, if it depended on some other condition:
if (someSpecialFlag && ... nameof(PropertyA)) ...
In such a case, I would put a prominent comment at the top of the cs code-behind file, alerting anyone who has to maintain the code that something special was done in OnPropertyChanged
.
Its also worth looking into Triggers
, as a way to represent conditions in XAML
.