【问题标题】:Simple Property Binding Not Working in XAML简单的属性绑定在 XAML 中不起作用
【发布时间】: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 来定义控件,然后在表单中使用这些控件。
  • 所以如果你想使用你的控件,请查看依赖属性,这里有很多例子

标签: .net wpf xaml binding


【解决方案1】:

您没有设置视图的DataContext。在您视图的构造函数中尝试做

DataContext = this;IntializeComponents() 方法调用之后。

【讨论】:

  • 我尝试了 DataContext=Me xaml 以及代码页,但结果仍然相同。也尝试了 DataContext = this,但我在 VB.net 中,所以我使用了我。错误仍然存​​在。
  • DataContext="Me" 来自 xaml 并在后面的代码中执行此操作
  • 我的构建器出现了一些错误,系统重启后它按照你说的方式工作,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多