问题
I have the problem, that my CanSave
method doesn't get called, when I change a binded property.
View
The View contains of some Labels
and TextBoxes
... nothing special...
The TextBoxes are binded to the properties of an object.
<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
The ViewModel defines the property NewBook
and the methods CanSaveBook
and SaveBook
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();
}
What I want is, that the Save-Button
is only available, when CanSaveBook
returns true
but that the CanSaveBook
-Method is checked after the user enters information in the textboxes... what am I missing?
回答1:
The problem you are having is that changing a property of the book does not raise INotifyPropertyChange on the view model. Easiest would be to get rid of the Book class and put the Name, Price, ISBN properties straight in the view model. Then raise INotifyPropertyChange in the setters (and make sure that the binding is two-way).
You can then construct the Book in the SaveBook method and call your service with it.
来源:https://stackoverflow.com/questions/32333022/wpf-caliburn-micro-canexecute-when-property-of-binded-object-changes