XAML C#在MVVM中,如何获取默认值转换器的结果

cbwuti44  于 2023-06-27  发布在  C#
关注(0)|答案(1)|浏览(78)

当我在TextBox控件中输入文本“abc”时,

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

其中V1是ViewModel中的UInt16属性

private UInt16 _V1;
    public UInt16 V1
    {
        get { return _V1; }
        set { SetProperty(ref _V1, value); }
    }

UI将通知验证错误,但在ViewModel的EventHandler中,我无法找到发生的错误,以及实际输入的文本。那么什么是正确的方法呢,谢谢

wixjitnu

wixjitnu1#

要将数据从UI发送到VM,首先需要将绑定模式设置为TwoWay

<TextBox Text="{Binding TextInput, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

然后,您需要调整ViewModel以公开string属性,因为TextBox.Textstring属性,因此不能直接双向绑定到数值类型。
相反,您可以在VM中使用2个属性。

  • 一个用于原始字符串。
  • 一个用于数值。

根据您的需要,您可以从一个属性的setter设置另一个属性。

private string _textInput;
public string TextInput
{
    get { return _textInput; }
    set 
    { 
        if (_textInput != value)
        {
            SetProperty(ref _textInput, value);
        
            // Validate that value is valid, then set the V1 property. 
            if (UInt16.TryParse(value, out var number))
            {
                V1 = number;
            }
        }
    }
}

private UInt16 _V1;
public UInt16 V1
{
    get { return _V1; }
    set
    { 
        if (_V1 != value)
        {
            SetProperty(ref _V1, value);
            
            // You can set TextInput automatically when setting V1.
            TextInput = value.ToString();
        }
    }
}

请注意,我添加了一些if检查,以防止无限更新的堆栈溢出。

相关问题