WPF消防PropertyChanged当用mvvm更新
问题描述:
我试图在我的应用程序中实现mvvm。我有绑定的命令,我需要火灾事件当用户输入一些数据到文本框为强制更新CanExecute
命令 我的视图模型WPF消防PropertyChanged当用mvvm更新
public class AddEditWindowViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
......
public ConfirmCommand ConfirmCommand { get; set; }
public string Path{ get; set; }
public AddEditWindowViewModel()
{
WindowTitle = "Add new item";
ConfirmCommand = new ConfirmCommand(this);
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
我的命令
public class ConfirmCommand: ICommand
{
private AddEditWindowViewModel _model;
public ConfirmCommand(AddEditWindowViewModel model)
{
_model = model;
_model.PropertyChanged += ModelOnPropertyChanged;
}
private void ModelOnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName.Equals("Path"))
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
public bool CanExecute(object parameter)
{
return !string.IsNullOrEmpty(_model.Path);
}
public void Execute(object parameter)
{
.....
}
public event EventHandler CanExecuteChanged;
}
我的观点
<Window x:Class="NameSpace.Views.AddEditWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:NameSpace.ViewModels"
mc:Ignorable="d"
Title="{Binding Path=WindowTitle}"
Height="200"
Width="500"
WindowStyle="SingleBorderWindow">
<Window.DataContext>
<vm:AddEditWindowViewModel />
</Window.DataContext>
.....
<TextBox Name="Path" Text="{Binding Path=Path, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="2" Grid.Column="0" Grid.Row="1"></TextBox>
.....
Button IsDefault="True" Command="{Binding Path=ConfirmCommand}" Margin="5" HorizontalAlignment="Right" Width="100" Grid.Row="2" Grid.Column="0" Content="Ok"></Button>
<Button IsCancel="True" Margin="5" HorizontalAlignment="Left" Width="100" Grid.Row="2" Grid.Column="1" Content="Cancel"></Button>
.....
当textbox u在ui中用户更新,PorpertyChanged
事件ConfirmCommand
不会触发。为什么? 我错了?
答
试图调用OnPropertyChanged在你的路径属性setter:
private string _path;
public string Path
{
get
{
return _path;
}
set
{
_path = value;
OnPropertyChanged();
}
}
答
您应提高PropertyChanged事件,如果(且仅当)的属性更改值:
private string _path;
public string Path
{
get
{
return _path;
}
set
{
if (_path != value)
{
_path = value;
OnPropertyChanged();
}
}
}
答
什么是你自己实施这样的事情:INotifyPropertyChanged
和ConfirmCommand
?有很多框架可以为你完成这个任务。还有很多MVVM方法,比如EventToCommand,ViewModelLocator,Messenger。例如https://msdn.microsoft.com/en-us/magazine/5eafc6fc-713a-4461-bc2b-469afdd03c31?f=255&MSPPError=-2147217396
其工作,谢谢:) –