Reputation: 35
I was making an app in which I needed to change the text of entry so that user can get old data and add new data in same place. The code I used:
for viewmodel:
[ObservableProperty]
string name;
RelayCommand]
public void PreviousData()
{
name = "Test";
}
for xaml:
<Entry Text="{Binding Name}"
Grid.Row="0"
Grid.Column="1"
BackgroundColor="White"/>
<Button Text="Previous"
Command="{Binding PreviousDataCommand}"
Grid.Row="4"
Grid.Column="0"/>
I was using it in:
I tried using binding for entry in net maui. I was expecting to be able to edit content in entry from code.
Upvotes: 1
Views: 2049
Reputation: 3917
The fields are named with underscore, when there is a property to modify them.
It is:
string _name;
And it will generate a property:
string Name;
If you do not follow naming conventions, writing one lower case letter can lead to so many bugs... and it is so hard to find. Lets say that there is a reason for them.
(Also, There is no bug in CommmunityToolkit.MVVM 8.1.0 I have been using it for a while, and I do have properties named "Name". Sometimes to make it working, you will have to clear all errors and rebuild, sometimes it will need to restart VS2022, but it happens really rare, and is a problem of the environment before everything else.)
Upvotes: 1
Reputation: 14469
You need to change the name = "Test";
to Name = "Test";
The official document said:
Fields with [ObservableProperty] should not be directly referenced, and the generated properties should be used instead. This warning exists to help avoid cases where developers accidentally refer to backing fields of a generated property to update its value, and then see no property change notification being raised. The generated property should always be referenced instead.
So the viewmodel should be such as:
[ObservableProperty]
string name;
[RelayCommand]
public void PreviousData()
{
Name = "Test";
}
In addition, it seems there is a bug in the CoummunityToolkit.Mvvm 8.1.0. When I used it and change the name to Name, it will throw an error. So I used the CoummunityToolkit.Mvvm 8.0.0 and everything worked well.
Upvotes: 2