我遇到问题,当我更改绑定属性时,我的CanSave
方法没有被调用。
视图包含一些Labels
和TextBoxes
......没什么特别的......
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
以及方法CanSaveBook
和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();
}
我想要的是,Save-Button
仅在CanSaveBook
返回true
时可用,但在用户输入信息后检查CanSaveBook
- 方法文本框...我错过了什么?
答案 0 :(得分:2)
您遇到的问题是更改图书的属性不会在视图模型上引发INotifyPropertyChange。最简单的方法是摆脱Book类并将Name,Price,ISBN属性直接放在视图模型中。然后在setter中引发INotifyPropertyChange(并确保绑定是双向的)。
然后,您可以在SaveBook方法中构建Book并使用它来调用您的服务。