C# 从代码隐藏执行命令时未设置MVVM模型属性
我通过文本框键控事件在ViewModel上执行命令。我面临的问题是,当执行命令时,绑定到ViewModel上属性的TextBox中的文本(仍然)为空 视图模型:C# 从代码隐藏执行命令时未设置MVVM模型属性,c#,wpf,mvvm,C#,Wpf,Mvvm,我通过文本框键控事件在ViewModel上执行命令。我面临的问题是,当执行命令时,绑定到ViewModel上属性的TextBox中的文本(仍然)为空 视图模型: private string _myText; public string MyText { get { return _myText; } set { _myText = value; RaisePropertyChanged("MyText"); } } // ..
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:
绑定和命令都可以工作。当使用按钮以正常方式执行命令时,属性设置得很好
我这样做不对吗 Set
UpdateSourceTrigger=PropertyChanged
默认情况下会在失去焦点时更新MyText
:
Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
此外,这与您的问题无关,但您可以为文本框创建输入绑定
,以便在按下Enter键时执行一些命令
:
<TextBox x:Name="tbTest" Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding MyCommand}"/>
</TextBox.InputBindings>
</TextBox>
尝试将文本属性的绑定更改为:
Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
我真的很喜欢输入绑定的建议。使用MVVM,我宁愿不从代码隐藏处执行命令。
<TextBox x:Name="tbTest" Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding MyCommand}"/>
</TextBox.InputBindings>
</TextBox>
Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"