无法使用CommandParameter更新字符串属性

时间:2017-09-21 19:41:26

标签: c# wpf xaml mvvm

我的应用程序使用自定义数字小键盘来填充我的文本框。这是我的xaml

<TextBox x:Name="myTextBox" Text="{Binding MyText}">
    <TextBox.InputBindings>
        <MouseBinding MouseAction="LeftClick" Command="{Binding KeyPad}" CommandParameter="{Binding MyText}"/>
    </TextBox.InputBindings>
</TextBox>

MyText是一个字符串ViewModel属性,KeyPad是一个RelayCommand

在我的ViewModel中:

    public string MyText { get => _myText; set => SetProperty(ref _myText, value); }
    public RelayCommand KeyPad { get => _kpUnitField; set => _kpUnitField = value; }
    public MyViewModel()
    {
        KeyPad = new RelayCommand(execute => KeyPad_Callback(execute), canExecute => true);
    }

KeyPad_Callback函数调用键盘窗口,实现了INotifyPropertyChanged,其他所有内容的View - ViewModel通信工作正常。

我的问题是TextBox没有更新。如果更改CommandParameter以绑定ElementName:

<MouseBinding MouseAction="LeftClick" Command="{Binding KeyPad}" CommandParameter="{Binding ElementName=myTextBox}"/>

它更新TextBox但不更新属性。

这是我在这里发表的第一篇文章。通常我所有的疑问都会回答已经提出的问题。对不起,如果我不够清楚。

修改

Ed Ednket在这里问了de KeyPad_Callback:

    private void KeyPad_Callback(object parameter) 
    {
        var keyPad = new NumKeyPad(parameter) // It's a window class that receives a string as argument 
        var retVal = keyPad.ShowDialog();
        if(retval == true)
        {
            parameter = keyPad.Result; //Result is a string Property
        }
    }

编辑 - 替代方法 根据这个 tek-tips.com/viewthread.cfm?qid=1669331

问题在于字符串的工作方式。类包装器可以解决它。

所以我创建了一个简单的Field类,这样我就可以对该字段的Label和TextBox字符串进行分组,并在CommandParameter参数中传递该类。现在它正在工作&#34;。

如果有人找到直接使用琴弦的方法,我会很感激,但现在感谢所有人的答案。

1 个答案:

答案 0 :(得分:-1)

您需要执行以下操作:

  1. 你的ViewModel应该继承INotifyPropertyChanged或BindableBase,我看到你这样做是因为这行 SetProperty(ref _myText, value);
  2. Text="{Binding MyText}"应更改为 Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}"

  3. 如果你需要双向绑定,那么它应该是 Text="{Binding MyText,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

  4. 阅读Kevin Cook的反馈意见。