【问题标题】:MVVM Model-property not set when command is executed from code-behind从代码隐藏执行命令时未设置 MVVM 模型属性
【发布时间】:2014-02-19 16:11:34
【问题描述】:

我通过 TextBox-KeyUp 事件在 ViewModel 上执行命令。我面临的问题是,绑定到 ViewModel 上的属性的 TextBox 中的文本在执行命令时(仍然)为空。

视图模型:

private string _myText;
public string MyText
{
    get { return _myText; }
    set 
    {
        _myText = value;
        RaisePropertyChanged("MyText");
    }
}

// ... ICommand stuff here

private object HandleMyCommand(object param)
{
    Console.WriteLine(MyText); // at this point MyText --> 'old' value, e.g. null
    return null;
}}

XAML:

<StackPannel>
    <TextBox x:Name="tbTest" KeyUp="TextBox_KeyUp" Text="{Binding MyText, Mode=TwoWay}" />
    <Button x:Name="btnTest" Content="Click" Command="{Binding MyCommand}" />
</StackPannel>

后面的代码:

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        if (btnTest.Command.CanExecute(null))
        {
            btnTest.Command.Execute(null);
        }
    }
}

绑定和命令都有效。当以正常方式执行命令时,使用按钮,属性设置得很好。

我没有正确执行此操作吗?

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    UpdateSourceTrigger=PropertyChanged 设置为默认MyText 将在失去焦点时更新:

    Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    

    同样,与您的问题无关,但是您可以为TextBox 创建InputBinding 以在按下 Enter 时执行一些Command

    <TextBox x:Name="tbTest" Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding MyCommand}"/>
        </TextBox.InputBindings>
    </TextBox>
    

    【讨论】:

    • 我真的很喜欢 InputBinding 的建议。使用 MVVM 我宁愿不从代码隐藏中执行命令。
    【解决方案2】:

    尝试将text属性的绑定改为:

    Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    

    【讨论】:

      猜你喜欢
      • 2013-03-04
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      相关资源
      最近更新 更多