I have a class called Commander
and it have a property called CurrentRound
and it gets updated every few seconds internally. I'm using CommunityToolkit.MVVM and In my viewmodel I declared an observable property called CurrentRound
and in the constructor of my viewmodel I did this currentRound = _commander.CurrentRound;
.
The strange thing is that when I put a breakpoint in my Commander class and pause the program, I can see the updated value in my xaml file(view) but not on the actual UI.
Commander Class:
public partial class Commander
{
private readonly Communication communication;
public Commander(Communication communication)
{
this.communication = communication;
ThreadStart work = this.NameOfMethodToCall;
Thread thread = new Thread(work);
thread.Start();
}
private async void NameOfMethodToCall()
{
while(true)
{
await Task.Delay(10000);
Console.WriteLine("hey I'm the second thread!");
CurrentRound = GetCurrentRound();
}
}
public int CurrentRound { get; private set; } = 1;
}
ViewModel:
public partial class ParametersViewModel: ObservableObject
{
public ParametersViewModel(Commander commander, ...)
{
_commander = commander;
currentRound = _commander.CurrentRound;
...
}
private readonly Commander _commander;
...
[ObservableProperty]
int currentRound;
...
}
View:
<Label
Text="{Binding CurrentRound, StringFormat='Current Round = {0}'}"
HorizontalOptions="Center"
FontAttributes="Bold"
FontSize="Body"/>
...
UPDATE:
Still having the same issue!
ViewModel:
public partial class ParametersViewModel: ObservableObject
{
...
[ObservableProperty]
Commander myCommander;
...
}
View:
<Label
Text="{Binding MyCommander.CurrentRound, ...
SECOND UPDATE:
This update solved my issue but I should make my Commander class inherits from ObservableObject and make its CurrentRound property an ObservableProperty, but when using MVVM design pattern I should not worry about UI in the models and business logic, but if I do this, I should care about UI bindings in the models right? isn't there a better ways of doing this?
Commander Class:
public partial class Commander: ObservableObject
{
...
[ObservableProperty]
int currentRound = 1;
...
}
Just want to point out something.
Considering:
And:
currentRound is a field. CurrentRound is a property.
Setting fields does not call code. Setting properties does.
All the problems you had, comes from no following naming conventions. Property A has field _a, not a.