gpt4 book ai didi

wpf - Prism :必须显式调用 RaiseCanExecuteChanged()

转载 作者:行者123 更新时间:2023-12-03 10:20:16 25 4
gpt4 key购买 nike

下面是一个很简单的Prism.WpfDelegateCommand 为例两者都有ExecuteCanExecute代表。

假设 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com