当绑定对象的属性发生变化时,WPF Caliburn Micro可以执行



我有问题,我的CanSave方法不被调用,当我改变绑定属性。

<标题> 视图

View包含一些LabelsTextBoxes…没什么特别的…

textbox被绑定到一个对象的属性。

<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 h1> 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,并使用它调用您的服务。

相关内容

  • 没有找到相关文章

最新更新