我在 WPF 中有一个基本项目。
它所做的一切都是检索/更新产品。
如下图所示,用户输入一个ID,然后根据它显示数据,用户可以更改数据并单击“保存产品”将其保存到数据库中。
GetProduct(int id)
函数通过提供的 ID 检索产品。SaveProduct()
函数保存更改的字段。
此外,还有两个 DataTemplate:
1) 对于 ProductModel - 包括 3 个文本框:ProductId、ProductName、UnitPrice。
2) 对于 ProductViewModel - 包括保存/获取按钮 + 一个文本框,供用户输入所需产品的 id。
我要做的是在用户单击“保存产品”按钮时获取更改的数据。
我认为最理想的方式是使用 Binding
.
每个文本框都已绑定(bind),但我不知道如何获取绑定(bind)数据。
以下是 FIRST DataType (ProductModel) 中绑定(bind)文本框的示例:<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding ProductId}" Margin="5" Width="150" />
以下每个属性都有一个:ProductId
, ProductName
和 UnitPrice
.
重要!: Get/SaveProduct()
函数在ProductViewModel class
,而实际的产品类别是 - 你猜对了 - ProductModel
. ProductViewModel
类包含一个包含当前显示产品的变量。
这是用于保存信息的按钮 - 它以 SECOND DataType (ProductViewModel) 编写:<Button Content="Save Product" DockPanel.Dock="Right" Margin="10,2" VerticalAlignment="Center" Command="{Binding Path=SaveProductCommand}" Width="100" />
SaveProductCommand
命令只是触发 SaveProduct()
功能。
我对整个主题有几个问题:
{Binding ProductId}
? DataType
在 DataTemplate
包括绑定(bind)的对象? <ContentControl Margin="10" Content="{Binding Path=CurrentProduct}" />
.它的目的是什么?
SaveProduct()
中获取值?功能?我只是引用,比如说CurrentProduct.ProductName
获得更改后的名称? 非常感谢所有花时间回答的人 - 我非常感谢!
最佳答案
What does it mean when a binding is used like this : {Binding ProductId} ?
设置此绑定(bind)的特定控件属性将查找
ProductId
对象上的属性设置为 DataContext
并相应地设置控件中的属性值。The default binding mode for textboxes is TwoWay as far as I remember. But in this case, ProductId/Name + UnitPrice are not dependency properties, therefore is it right that the binded values do not update/sent back when the text in the textboxes is changed? (Since there isn't an event attached to it...)
您不需要将对象中的属性设为
DependencyProperty
对于 TwoWay
发生绑定(bind)。A data context was never configured in my project, but all of the "binding tags" in my XAML pages don't seem to have a defined source. Could it be that the source is actually the DataType in the DataTemplate that includes the binded objects?
在 XAML 中设置的绑定(bind)将使用存储在
DataContext
中的对象。 ,因此如果您没有明确设置 DataContext
在 View 中,它将为空。但是您应该注意 DataContext
是从其父代继承而来的。如果您实际上是通过使用 CurrentProduct
来设置内容,那么所有属性都可以根据您的 Product
绑定(bind)到类型。The SECOND DataTemplate (the ProductViewModel one) has this ContentControl tag:
<ContentControl Margin="10" Content="{Binding Path=CurrentProduct}" />
What is it's purpose?
它充当您的
CurrentProduct
的容器。 ,其中可以包含一项且仅一项。If a TwoWay binding were/does occur, how do I get the values from within the SaveProduct() function? Do I just refer to, say CurrentProduct.ProductName to get the changed name?
在没有看到整个应用程序的情况下,我的猜测是
ContentControl
正在设置为 CurrentProduct
和你的TextBox
等都绑定(bind)到各自的属性,如CurrentProduct.ProductId
等...您要保存的产品实际上是CurrentProduct
.当您在 ViewModel 中调用 save 时,您只需访问 CurrentProduct
并根据需要保留它,其中 CurrentProduct.PropertyName
将包含从 UI 传播的更改。
关于c# - 使用 WPF/C# 中的绑定(bind)获取更改的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114165/