作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面是一个很简单的Prism.Wpf
以 DelegateCommand
为例两者都有Execute
和 CanExecute
代表。
假设 CanExecute
取决于某些属性。看来 Prism 的DelegateCommand
不重新评估 CanExecute
当此属性更改时自动条件,如 RelayCommand
在其他 MVVM 框架中确实如此。相反,您必须在属性 setter 中显式调用 RaiseCanExecuteChanged()。这会导致在任何重要的 View 模型中出现大量重复代码。
有没有更好的办法?
View 模型:
using System;
using Prism.Commands;
using Prism.Mvvm;
namespace PrismCanExecute.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Unity Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private string _name;
public string Name
{
get { return _name; }
set
{
SetProperty(ref _name, value);
// Prism doesn't track CanExecute condition changes?
// Have to call it explicitly to re-evaluate CanSubmit()
// Is there a better way?
SubmitCommand.RaiseCanExecuteChanged();
}
}
public MainWindowViewModel()
{
SubmitCommand = new DelegateCommand(Submit, CanSubmit);
}
public DelegateCommand SubmitCommand { get; private set; }
private bool CanSubmit()
{
return (!String.IsNullOrEmpty(Name));
}
private void Submit()
{
System.Windows.MessageBox.Show(Name);
}
}
}
<Window x:Class="PrismCanExecute.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
Title="{Binding Title}"
Width="525"
Height="350"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<!--<ContentControl prism:RegionManager.RegionName="ContentRegion" />-->
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: " />
<TextBox Width="150"
Margin="5"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Width="50"
Command="{Binding SubmitCommand}"
Content="Submit" Margin="10"/>
<!--<Button Width="50"
Content="Cancel"
IsCancel="True" Margin="10"/>-->
</StackPanel>
</StackPanel>
</Grid>
</Window>
最佳答案
正如@l33t 解释的那样,这是设计的。如果您希望 DelegateCommand 自动监视 VM 属性的更改,只需使用 delegateCommand 的 ObservesProperty 方法:
var command = new DelegateCommand(Execute).ObservesProperty(()=> Name);
关于wpf - Prism :必须显式调用 RaiseCanExecuteChanged(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38958379/
我是一名优秀的程序员,十分优秀!