简体   繁体   English

ms mvvm 工具包:无法弄清楚如何连接 ReplayCommand 和 canExecute

[英]ms mvvm toolkit: can't work out how to wire up ReplayCommand and canExecute

I have a simple model:我有一个简单的 model:

public sealed partial class ResultsModel : ObservableObject {

    [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
    [NotifyCanExecuteChangedFor(nameof(ClearCommand))]
    [ObservableProperty]
    ObservableCollection<Arrivals> _arrivals = new();

    public RelayCommand SaveCommand { get; private set; }
    public RelayCommand ClearCommand { get; private set; }

    internal ResultsModel() {
        SaveCommand = new RelayCommand(SaveRequest, CanSaveClear);
        ClearCommand = new RelayCommand(OnClear, CanSaveClear);
    }

    public bool CanSaveClear() {
        return _arrivals.Count > 0;
    }

    void OnClear() {
        _arrivals.Clear();
    }

    async void SaveRequest() {
    // save stuff
    }
}

// c#
DataContext = (model = new ResultsModel());
...
model.Arrivals.insert(0, thing); 

// The _arrivals are bound to an ItemsRepeater and appear in gui as //they're added
<ItemsRepeater ItemsSource="{Binding Arrivals}">
<Button Content="Clear" Command="{Binding ClearCommand}"/>
<Button Content="Save" Command="{Binding SaveCommand}" />

I've bound buttons to the two Commands and they work ok, I just can't work how to get the canExecute code to run more than one time.我已经将按钮绑定到这两个命令并且它们工作正常,我只是无法工作如何让 canExecute 代码运行不止一次。

I was expecting that when items get added to the _arrivals collection (and they do) the canExecutes would be re-evaluated via the NotifyCanExecuteChangedFor attribute, but I'm obviously missing some glue somewhere because the button are always disabled.我期待当项目被添加到 _arrivals 集合中时(他们确实这样做了),canExecutes 将通过 NotifyCanExecuteChangedFor 属性重新评估,但我显然在某处缺少一些胶水,因为按钮总是被禁用。

Any help would be appreciated.任何帮助,将不胜感激。

It won't happen when you added an item to the Arrivals .当您将项目添加到Arrivals时,它不会发生。 But it will happen when you change the Arrivals by giving a new ObservableCollection .但是,当您通过提供新的ObservableCollection来更改Arrivals时,就会发生这种情况。 You could create a simple string property to test this behavior.您可以创建一个简单的字符串属性来测试此行为。

The reason for this behavior is that when the NotifyCanExecuteChangedFor Attribute is used, the IRelayCommand.NotifyCanExecuteChanged will be called when the setter of the property is called.出现这种行为的原因是当使用NotifyCanExecuteChangedFor属性时,会在调用该属性的 setter 时调用IRelayCommand.NotifyCanExecuteChanged In your scenario, that means only when the setter of the Arrivals property is called, this Attribute will call the IRelayCommand.NotifyCanExecuteChanged .在您的场景中,这意味着只有在调用Arrivals属性的设置器时,此属性才会调用IRelayCommand.NotifyCanExecuteChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM