簡體   English   中英

綁定對象的屬性更改時,WPF Caliburn Micro CanExecute

[英]WPF Caliburn Micro CanExecute when property of binded object changes

我有問題,當我更改綁定屬性時,我的CanSave方法不會被調用。

視圖

視圖包含一些LabelsTextBoxes ...沒什么特別的......

TextBoxes綁定到對象的屬性。

<Label Target="{Binding ElementName=txtTitle}" Grid.Column="0" Grid.Row="0" Content="Titel" Foreground="White" />
<TextBox Name="txtTitle" Grid.Column="1" Grid.Row="0" Text="{Binding NewBook.Title}" />

<Label Target="{Binding ElementName=txtAuthor}" Grid.Column="0" Grid.Row="1" Content="Autor" Foreground="White" />
<TextBox Name="txtAuthor" Grid.Column="1" Grid.Row="1" Text="{Binding NewBook.Author}"/>

<Label Target="{Binding ElementName=txtIsbn}" Grid.Column="0" Grid.Row="2" Content="ISBN" Foreground="White" />
<TextBox Name="txtIsbn" Grid.Column="1" Grid.Row="2" Text="{Binding NewBook.Isbn}" />

<Label Target="{Binding ElementName=txtPrice}" Grid.Column="0" Grid.Row="3" Content="Preis" Foreground="White" />
<TextBox Name="txtPrice" Grid.Column="1" Grid.Row="3" Text="{Binding NewBook.Price}"/>

<Button Grid.Column="1" Grid.Row="4" Content="Speichern" Name="SaveBook" />

視圖模型

ViewModel定義了NewBook屬性以及CanSaveBookSaveBook方法

public Book NewBook
{
    get { return this.newBook; }
    set
    {
        this.newBook = value;
        this.NotifyOfPropertyChange(() => this.NewBook);
        this.NotifyOfPropertyChange(() => this.CanSaveBook);
    }
}

public bool CanSaveBook
{
    get
    {
        return !string.IsNullOrEmpty(this.NewBook.Title) 
                && !string.IsNullOrEmpty(this.NewBook.Author)
                && !string.IsNullOrEmpty(this.NewBook.Isbn) 
                && this.NewBook.Price != 0;
    }
}

public void SaveBook()
{
    try
    {
        this.xmlOperator.AddBook(ConfigurationManager.AppSettings.Get("BookXmlPath"), this.NewBook);
    }
    catch (Exception ex)
    {
        throw ex;
    }

    this.NewBook = new Book();
}

我想要的是, Save-Button僅在CanSaveBook返回true時才可用,但是在用戶在文本框中輸入信息后檢查CanSaveBook ...我錯過了什么?

您遇到的問題是更改圖書的屬性不會在視圖模型上引發INotifyPropertyChange。 最簡單的方法是擺脫Book類並將Name,Price,ISBN屬性直接放在視圖模型中。 然后在setter中引發INotifyPropertyChange(並確保綁定是雙向的)。

然后,您可以在SaveBook方法中構建Book並使用它來調用您的服務。

暫無
暫無

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

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