簡體   English   中英

如何讓 Prism 的 DelegateCommand 觀察子視圖模型的屬性?

[英]How can I make Prism's DelegateCommand observe a child view-model's property?

我的“父”視圖模型 ( AnalyzeVm ) 有一個子視圖模型 ( ScanVm ),它表示可以保存到磁盤的內容。 我想給父級一個命令 ( SaveCmd ),該命令僅在ScanVm.IsDirty屬性為真時才啟用。

我已經在各處使用了DelegateCommand及其ObservesProperty函數,因此我嘗試將其用於此目的。 但在這種情況下,我無法獲得ObservesProperty表達式來觸發對CanExecute的調用。

這里的區別(與我使用ObservesProperty的所有其他地方工作正常)是我正在監視孩子 object 的財產。不是我自己的

我需要了解為什么這不起作用。 我認為這是一件有效的事情。

這是兩個視圖模型(為清楚起見被剝離)

// Parent view-model.  Derives from a class that implements INotifyPropertyChanged.

public class AnalyzeVm : BaseViewModel
{
    private ScanVm _scan;

    public AnalyzeVm(ScanVm scan)
    {
        _scan = scan;

        // Set up the command.  Try to make it monitor a property of the ScanVm
        // object instead of one of our own.

        SaveScanCmd = new DelegateCommand(
            () => { _scan.Save() }                 // execute -- saves the scan
            () => { return _scan.IsDirty; })       // only valid when scan is dirty
            .ObservesProperty(() => scan.IsDirty); // So observe IsDirty property

        // Now just as a sanity check, add a handler for that property changing
        // to the PropertyChangedEventManager and log when it does.

        PropertyChangedEventManager.AddHandler(
            scan, 
            (_, _) => Debug.WriteLine("IsDirty changed"), 
            nameof(ScanContext.IsDirty));
    }

    public ICommand SaveScanCmd { get; }

    // other code...
}

// ScanVm class.  

public class ScanVm : BaseViewModel
{
    private bool _isDirty;
    public bool IsDirty
    { 
        get => _isDirty;
        set => SetProperty(ref _isDirty, value);  // Raises PropertyChanged event
    }
    public void Save()
    {
        // Code here to save the ScanVm
       
        IsDirty = false;  // No longer dirty
    }
    // ... other code
}

我確信IsDirty屬性正在正確更改並觸發事件。 我確認了很多次。 當我觀察我自己的類的屬性時,我已經成功地使用了Observes屬性。 例如,我SaveCmd ScanVm class 本身——這樣屬性表達式就觀察到ScanVm自己的屬性,然后它就可以正常工作了。 我在我的代碼中到處都是這樣做的。

這是我試圖觀察另一個對象的屬性的唯一地方。 這樣做有效嗎? 如果是這樣,我做錯了什么?

ObservesProperty主要作用於包含 object 的屬性

public bool IsDirty {...}

...ObservesProperty( () => IsDirty );

加上嵌套屬性

public ScanVM Child {...}

...ObservesProperty( () => Child.IsDirty );

它只是不觀察任何給定實例的屬性,因為它從包含AnalyzeVm (在本例中為 AnalyzeVm)開始查找。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM