wpfbinding

WPF, how to handle string entered into TextBox bound to integer


I have a Prism project: CustomerView, CustomerViewModel, CustomerModel. Latter has property

private int _id;
public int ID
{
    get { return _id; }
    set { SetProperty(ref _id, value); }
}

CustomerView has a TextBox to display the ID. What I want - ability to handle the situation when user enters some string into that TextBox. Handle either in CustomerModel or CustomerViewModel. Property setter on CustomerModel.ID never fires if user enters a string like "1abc". I do know about ValidationRules, but thats not what I need. I want to get that "1abc"


Solution

  • Get the string and convert it to int

    private string _id;
    public string ID
    {
        get { return _id; }
        set { SetProperty(ref _id, value); if (int.TryParse(value, out int num)) IntID = num; }
    }
    
    private int _intId;
    public int IntID
    {
        get { return _intId; }
        private set { SetProperty(ref _intId, value); }
    }