【问题标题】:c# wpf Binding Command - access value of textbox from commandc# wpf Binding Command - 从命令访问文本框的值
【发布时间】:2012-12-26 18:21:23
【问题描述】:

我想调用一个简单的命令,它将我的 GUI 中的值添加到数据库中。

我的命令:

private ICommand addSpeechCommand;
public ICommand AddSpeechCommand
{
  get
  {
    if (addSpeechCommand == null)
    {
      addSpeechCommand = new RelayCommand(param => AddSpeech());
    }
    return addSpeechCommand;
  }
}

public void AddSpeech()
{
  // TODO add 
OrganizerBL.InsertSpeech(new Speech(maxSpeechId, currentSpeech.Title, currentSpeech.Summary, currentSpeech.Start, currentSpeech.End, currentSpeech.TrackId, currentSpeech.SpeakerId, currentSpeech.ConferenceId, currentSpeech.Room));
  this.LoadSpeeches();
}

——这个被注释掉的行显示了当我的数据网格的一行被选中时我是如何处理它的。但我希望它在没有 currentSpeech 的情况下工作

我的 XAML:

        <Label x:Name ="lblTitle" Content="Title"/>
        <TextBox x:Name="txtTitle" Text="{Binding CurrentSpeech.Title, Mode=TwoWay}" Margin="2,144,0,0" Height="20" VerticalAlignment="Top"/>

和其他文本框...

我真的不知道如何从命令中访问文本框的值来调用我的 insertSpeech 方法...

对不起我的英语:)

更新: 我得到一个空引用异常,因为我的 currentSpeech 为空。 没有 currentSpeech 有没有办法解决这个问题?

【问题讨论】:

  • 在哪里绑定 AddSpeechCommand ?是按钮还是其他东西?

标签: wpf xaml mvvm command


【解决方案1】:

您得到 NullReferenceException 的原因可能是因为它是在属性本身中实例化的。当您创建绑定时,它会在该阶段创建到属性。并且当它为 NULL 时绑定到该属性。 IT 实际上是在属性内部创建的,但 Binding 永远不会知道这一点。

首先,我会从属性中删除所有逻辑。 我还将在类中实现 INotifyPropertyChanged,并在属性的“集合”中调用 PropertyChanged。这意味着 UI 将知道该属性的任何更改。 然后,如果它在任何 Binding ot XAML 中使用,我将为该属性创建一个依赖属性。

最后,我将在类的构造函数中实例化命令。

逻辑(在我的书中)不属于属性。

【讨论】:

    【解决方案2】:

    怎么做
    1.绑定TextBox.Text到View模型属性
    2.在Command Handler中使用View模型属性。


    在您的情况下,您已将TextBox.Text 绑定到CurrentSpeech.Title,但使用this.Title

    在您的命令中,将this.Title 更改为currentSpeech.Title

    【讨论】:

    • 你好,谢谢。这是我的一个错误,但是如果我尝试通过我的添加按钮添加语音,我会得到一个空引用异常,因为 currentsSpeech 是空的 ...
    • 你应该在视图模型构造函数中初始化currentSpeech,然后绑定currentSpeech的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多