的绑定对象更改WPF卡利微CanExecute时财产绑定、卡利、财产、对象

2023-09-05 03:09:59 作者:南巷*

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

I have the problem, that my CanSave method doesn't get called, when I change a binded property.

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

The View contains of some Labels and TextBoxes... nothing special...

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

The TextBoxes are binded to the properties of an object.

<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​​ 和方法 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();
        }

我要的是,该保存键式仅当 CanSaveBook 返回但该 CanSaveBook - 方法后,用户被选中在文本框中输入信息......我缺少什么?

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?

推荐答案

您遇到的问题是,改变图书的属性不会提升INotifyPropertyChange的视图模型。最简单的办法是摆脱Book类,并把名称,价格,ISBN性能直在视图模型。然后提高INotifyPropertyChange的制定者(并确保绑定是双向的)。

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).

您可以进而构建本书在SaveBook方法,并用它打电话给你的服务。

You can then construct the Book in the SaveBook method and call your service with it.