raihane
raihane

Reputation: 39

Validation and NotififyOnValidation Error don't work

I have a property Name which is required in the model. Then in the VM I have a Name property that access the one of the model. And in my view I bind a textbox with the Name property of the VM. But the textbox does not get in red when it is empty. I do get the error : Field Name is required. But once again the textbox does not turn red. Please help

here is the model :

public class Task : BasicAuditTrail
{

    [Required]
    [MaxLength(256)]
    public string Name { get; set; }
}

Here is the VM :

public class TaskManagerViewModel : ViewModelBase, ITaskManagerViewModel
{
    public Task CurrentTask => taskManager.CurrentTask;

    public string Name
    {
        get
        {
            return CurrentTask.Name;
        }
        set
        {
            CurrentTask.Name = value;
            IsDirty = true;
            RaisePropertyChanged();
        }
    }

The View :

<TextBox Grid.Row="0" Grid.Column="3" Name="Name" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" />

Upvotes: 0

Views: 24

Answers (1)

Shivani Katukota
Shivani Katukota

Reputation: 859

As mentioned in comments, the Name property of CurrentTask should be directly bind to the Textbox. This makes the error to work correctly.

To set the IsDirty property on the viemwodel, subscribe to the PropertyChanged event of the CurrentTask and set IsDirty there!

PS: make sure to remove the event when the CurrentTask is changing so as to not have any memory leaks

Upvotes: 1

Related Questions