Search code examples
c#wpfmvvm-light

Doesn't take the result from View to ViewModel MVVM light


My ViewModel Doesn't take the value from model

I create the model

public class UserModel : INotifyPropertyChanged
{
    private string firstName;


    public string Firstname
    {
        get => firstName;
        set
        {
            firstName = value;
            NotifyPropertyChanged("Firstname");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

my view model

UserModel user = new UserModel();
public UserModel User
{
    get => user;
    set => Set(ref user, value);
}

and in model I bind with this line User.FirstName

<TextBox x:Name="FirstName" Style="{StaticResource FirstNameBox}" Grid.Column="2" Grid.Row="2" >
    <TextBox.Text>
        <Binding  Mode="TwoWay" Path="User.FirstName" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <DataErrorValidationRule ValidatesOnTargetUpdated="False"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>

but I take null. take example frome this answer mvvm calculated fields


Solution

  • The binding paths are case-sensitive. You should bind to User.Firstname or change the name of the property to FirstName:

    public string FirstName
    {
        get => firstName;
        set
        {
            firstName = value;
            NotifyPropertyChanged("Firstname");
        }
    }