Mvvm 为什么DelegateCommand对Button和MenuItem的作用不同?
此代码显示与菜单项和按钮一起使用时的工作方式不同:Mvvm 为什么DelegateCommand对Button和MenuItem的作用不同?,mvvm,delegatecommand,Mvvm,Delegatecommand,此代码显示与菜单项和按钮一起使用时的工作方式不同: 通过按钮,命令方法可以访问ViewModel上已更改的OnPropertyChanged值 但是,在使用MenuItem时,命令方法无权访问已更改的OnPropertyChanged值 有人知道为什么会这样吗 MainView.xaml: <Window x:Class="TestCommand82828.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/200
- 通过按钮,命令方法可以访问ViewModel上已更改的OnPropertyChanged值
- 但是,在使用MenuItem时,命令方法无权访问已更改的OnPropertyChanged值
<Window x:Class="TestCommand82828.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:TestCommand82828.Commands"
Title="Main Window" Height="400" Width="800">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Command="{Binding DoSomethingCommand}" Header="Do Something" />
</MenuItem>
</Menu>
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
<Button Command="{Binding DoSomethingCommand}" Content="test"/>
<TextBlock Text="{Binding Output}"/>
<TextBox Text="{Binding TheInput}"/>
</StackPanel>
</DockPanel>
</Window>
using System;
using System.Windows;
using System.Windows.Input;
using TestCommand82828.Commands;
namespace TestCommand82828.ViewModels
{
public class MainViewModel : ViewModelBase
{
#region ViewModelProperty: TheInput
private string _theInput;
public string TheInput
{
get
{
return _theInput;
}
set
{
_theInput = value;
OnPropertyChanged("TheInput");
}
}
#endregion
#region DelegateCommand: DoSomething
private DelegateCommand doSomethingCommand;
public ICommand DoSomethingCommand
{
get
{
if (doSomethingCommand == null)
{
doSomethingCommand = new DelegateCommand(DoSomething, CanDoSomething);
}
return doSomethingCommand;
}
}
private void DoSomething()
{
Output = "did something, the input was: " + _theInput;
}
private bool CanDoSomething()
{
return true;
}
#endregion
#region ViewModelProperty: Output
private string _output;
public string Output
{
get
{
return _output;
}
set
{
_output = value;
OnPropertyChanged("Output");
}
}
#endregion
}
}
我认为您看到的是因为MenuItems不会将焦点从文本框移开,默认情况下,文本框仅在焦点从其移开时将更改推回到其绑定源。因此,当你点击按钮时,焦点转移到按钮,将文本框的值写回输入。但是,单击菜单项时,焦点仍保留在文本框中,因此不会写入值 尝试将文本框声明更改为:
<TextBox Text="{Binding TheInput,UpdateSourceTrigger=PropertyChanged}"/>
或者,尝试切换到DelegateCommand
,它可以接收参数,并将文本框的文本传递给它:
<MenuItem Command="{Binding DoSomethingCommand}"
CommandParameter="{Binding Text,ElementName=inputTextBox}" />
...
<TextBox x:Name="inputTextBox" Text="{Binding TheInput}" />
...
我认为您看到的是因为MenuItems不会将焦点从文本框移开,默认情况下,文本框仅在焦点从文本框移开时将更改推回其绑定源。因此,当你点击按钮时,焦点转移到按钮,将文本框的值写回输入。但是,单击菜单项时,焦点仍保留在文本框中,因此不会写入值
尝试将文本框声明更改为:
<TextBox Text="{Binding TheInput,UpdateSourceTrigger=PropertyChanged}"/>
或者,尝试切换到DelegateCommand
,它可以接收参数,并将文本框的文本传递给它:
<MenuItem Command="{Binding DoSomethingCommand}"
CommandParameter="{Binding Text,ElementName=inputTextBox}" />
...
<TextBox x:Name="inputTextBox" Text="{Binding TheInput}" />
...