Vic*_*jee 2 c# wpf binding mvvm
我是wpf的新手,我有这种情况.比方说,我有一个Customer与模型FirstName,LastName,Telephone等等.如果需要编辑现有客户的详细信息,CustomerEdit则在具有类型属性的位置打开viewmodel Customer.该视图包含一些文本框CurrentCustomer.FirstName,CurrentCustomer.LastName依此类推.现在,只要用户在这些文本框中提供输入,就会更新有界属性.有一个按钮用于保存所做的更改.有没有办法在按下保存按钮时更新源属性,如果可能,以MVVM方式?
默认为TextDP,UpdateSourceTrigger值为LostFocus.将其更改为Explicit保存按钮单击并通过获取绑定表达式并通过调用UpdateSource()来手动更新源.
XAML:
<TextBox x:Name="myTextBox"
Text="{Binding PropertyName, UpdateSourceTrigger=Explicit}"/>
<Button Click="btnSave_Click"/>
Run Code Online (Sandbox Code Playgroud)
代码背后:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
myTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
Run Code Online (Sandbox Code Playgroud)
在代码中使用此逻辑并不违反任何MVVM规则,但如果您不想在代码中使用它,那么仍然如此.你可以这样做:
ICommand在视图模型中创建一个并绑定到按钮命令,并在命令参数中传递textBox的文本值.您可以使用RelayCommand或根据DelegateCommand您的需要选择.对于DelegateCommand,请参阅此处.
<TextBox x:Name="myTextBox"
Text="{Binding PropertyName, UpdateSourceTrigger=Explicit}"/>
<Button Command="{Binding SaveCommand}"
CommandParameter="{Binding Text, ElementName=myTextBox}"/>
Run Code Online (Sandbox Code Playgroud)
并在ViewModel命令方法中设置textBox文本绑定到的实际值.
private void SaveMethod(object parameter)
{
this.PropertyName = parameter.ToString();
}
Run Code Online (Sandbox Code Playgroud)