WPF,如何处理输入到绑定到整数的 TextBox 中的字符串

问题描述 投票:0回答:1

我有一个 Prism 项目:CustomerView、CustomerViewModel、CustomerModel。后者有财产

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

CustomerView 有一个 TextBox 来显示 ID。我想要什么 - 当用户在文本框中输入一些字符串时能够处理这种情况。在 CustomerModel 或 CustomerViewModel 中处理。如果用户输入“1abc”等字符串,则 CustomerModel.ID 上的属性设置器永远不会触发。我确实了解 ValidationRules,但这不是我需要的。我想要得到那个“1abc”

wpf binding
1个回答
0
投票

获取字符串并将其转换为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); }
}
© www.soinside.com 2019 - 2024. All rights reserved.