You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF Prism项目中,如何处理绑定整数的TextBox输入的字符串?

解决Prism项目中获取TextBox原始输入值的问题

因为你的CustomerModel.ID是int类型,WPF默认绑定在遇到无法转换为int的字符串(比如"1abc")时,会跳过源属性的更新,所以setter不会触发。要获取原始输入值,可以通过以下两种方式实现:

方式一:在ViewModel中新增字符串属性中转

在CustomerViewModel里添加一个字符串类型的输入属性,直接绑定到TextBox,这样不管输入什么内容都能触发setter,拿到原始值后再自行处理与Model的同步:

private string _inputId;
public string InputId
{
    get => _inputId;
    set
    {
        if (SetProperty(ref _inputId, value))
        {
            // 这里直接拿到原始输入值,比如"1abc"
            if (int.TryParse(value, out int parsedId))
            {
                // 转换成功时更新Model的ID
                CustomerModel.ID = parsedId;
            }
            else
            {
                // 转换失败时可以处理原始值,比如给Model加个RawId属性存储
                CustomerModel.RawId = value;
            }
        }
    }
}

然后修改View中TextBox的绑定:

<TextBox Text="{Binding InputId, UpdateSourceTrigger=PropertyChanged}" />

UpdateSourceTrigger=PropertyChanged可以实时响应输入变化,若不需要实时,也可以保留默认的LostFocus。

方式二:在Model中新增原始值属性

直接在CustomerModel里添加一个字符串类型的属性来存储原始输入,ViewModel绑定这个属性,Model内部自行处理与ID的同步:

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

private string _rawId;
public string RawId
{
    get => _rawId;
    set
    {
        if (SetProperty(ref _rawId, value))
        {
            // 获取原始输入值
            if (int.TryParse(value, out int parsedId))
            {
                ID = parsedId;
            }
            // 这里可以对原始值做其他逻辑处理
        }
    }
}

然后ViewModel暴露Model的RawId属性,View绑定到这个属性即可。

内容的提问来源于stack exchange,提问作者Alexey Titov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 09:35:59