【问题标题】:WPF Caliburn Micro CanExecute when property of binded object changes当绑定对象的属性发生变化时,WPF Caliburn Micro CanExecute
【发布时间】:2015-09-01 13:32:19
【问题描述】:

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

查看

视图包含一些LabelsTextBoxes...没什么特别的...

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

<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-方法...我错过了什么?

【问题讨论】:

    标签: c# .net wpf mvvm caliburn.micro


    【解决方案1】:

    您遇到的问题是更改图书的属性不会在视图模型上引发 INotifyPropertyChange。最简单的方法是去掉 Book 类并将 Name、Price、ISBN 属性直接放在视图模型中。然后在设置器中引发 INotifyPropertyChange(并确保绑定是双向的)。

    然后您可以在 SaveBook 方法中构造 Book 并使用它调用您的服务。

    【讨论】:

    • 好吧,我也会这样做,但我认为有一个“更漂亮”的解决方案。还有一个棘手的问题:只有在退出最后一个文本框后才能启用按钮。如何在每次键入后执行 CanSaveBook 方法而无需任何代码隐藏?
    • 将 TextBox 上的 UpdateSourceTrigger 设置为 PropertyChanged(默认为 LostFocus)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多