WPF Caliburn Micro:当绑定对象的属性更改时,CanExecute如何执行

3
我有一个问题,当我更改绑定属性时,我的CanSave方法没有被调用。

视图

视图包含一些 标签文本框 ... 没有什么特别的...

这些文本框绑定到对象的属性。

<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" />

视图模型

视图模型定义了属性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();
}

我想要的是,当用户在文本框中输入信息后才检查CanSaveBook方法是否返回true,并且只有在其返回true Save-Button 可用……我缺少什么?

1个回答

2
你遇到的问题是更改书籍属性时没有在视图模型上引发INotifyPropertyChange。最简单的方法是摆脱Book类并将Name、Price、ISBN属性直接放在视图模型中。然后在setter中引发INotifyPropertyChange(并确保绑定是双向的)。
然后你可以在SaveBook方法中构建Book对象并调用你的服务。

好的,很酷,这也是我会做的事情,但我认为还有一个“更美丽”的解决方案。然而还有另一个问题:按钮只有在退出最后一个文本框后才能启用...如何在没有任何代码后台的情况下在每次键盘松开后执行CanSaveBook方法? - xeraphim
将您的TextBox的UpdateSourceTrigger设置为PropertyChanged(默认为LostFocus) - Z .

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接