【发布时间】:2015-01-03 21:40:33
【问题描述】:
一个简单的数据绑定不起作用,虽然我犯了一些错误,但无法弄清楚出了什么问题:
用户控件 Xaml:
<UserControl x:Class="PurchaseStockControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Text="{Binding Path=Namee}" DataContext="Me"/>
</Grid>
</UserControl>
我想绑定属性 namee:但结果是“System.Windows.Data 错误:40:BindingExpression 路径错误:在 'object' ''String' (HashCode=-840583197) 上找不到 'Namee' 属性”。 BindingExpression:Path=Namee; DataItem='String' (HashCode=-840583197); 目标元素是'TextBox' (Name=''); 目标属性是'Text' (类型'String')"。尽管我之前做了一些绑定,但我无法弄清楚这个错误并花了 2 天时间 :(。 控制代码:
Public Class PurchaseStockControl
Implements ComponentModel.INotifyPropertyChanged
Public Event PropertyChanged(sender As Object, e As ComponentModel.PropertyChangedEventArgs) Implements ComponentModel.INotifyPropertyChanged.PropertyChanged
Public Sub NotifyPropertyChanged(ByVal PropertyName As String)
RaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs(PropertyName))
End Sub
Property Namee As String
Get
Return "Some Value"
End Get
Set(value As String)
NotifyPropertyChanged("Namee")
End Set
End Property
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
End Class
带有用户控制的主窗口:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:z="clr-namespace:WPFApp"
Title="MainWindow" Height="600" Width="800">
<Grid>
<z:PurchaseStockControl x:Name="Test"/>
</Grid>
</Window>
【问题讨论】:
-
为什么要在后面的代码中实现 INotifyPropertyChanged?如果你想做 MVVM,你应该使用视图模型。如果你想做旧的 WinForm 风格,你可以使用 txtbox1.Text。如果您想创建用户控件以供重用,您应该查看依赖属性
-
@blindmeis:我不是编码专家,但仍在学习,我使用 MVVM 来定义控件,然后在表单中使用这些控件。
-
所以如果你想使用你的控件,请查看依赖属性,这里有很多例子