WPF 与 .NET 对象的绑定不传递数据 [英] WPF binding with .NET object not communicating the data

查看:27
本文介绍了WPF 与 .NET 对象的绑定不传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习有关 WPF 数据绑定的教程.我正在尝试将 .NET 对象的属性绑定到 XAML 控件,但该控件不显示预期的数据.这些是我认为的相关代码部分:

I am following a tutorial on WPF data binding. I am trying to bind to a .NET object's property to a XAML control but the control does not display the expected data. These are what I believe to be the relevant sections of code:

在程序代码中:(注意:在原帖后删除了 PhotoGallery 中的 ObservableCollection)

In procedural code: (Note: removed ObservableCollection in PhotoGallery after original post)

Namespace PhotoGallery
Partial Public Class MainWindow
  Inherits Window
  Private photos As New Photos
  ...
End Class

Namespace PhotoGallery
Public Class Photos
  Inherits Collection(Of Photo)
  ...
End Class

在 XAML 中(解决方案/项目名称为 Ch13-PhotoGallery):

In XAML (Solution/Project name is Ch13-PhotoGallery):

<Window x:Class="PhotoGallery.MainWindow"
    ...
    xmlns:local="clr-namespace:Ch13_PhotoGallery.PhotoGallery"
    ...>

<Window.Resources>
  <local:Photos x:Key="Photos"/>
</Window.Resources>

这是不显示数据的控件,即照片集合的大小:

And this is the control that is not displaying the data, which is the size of the Photos collection:

<Label x:Name="numItemsLabel" Background="AliceBlue" FontSize="8" Content="{Binding Source={StaticResource Photos}, Path=Count}"/>

当我输入 <标签 >,Intellisense 为 Path 属性弹出了计数",所以我认为这告诉我我已经正确定义了所有内容.

When I typed in the < Label >, Intellisense popped up 'Count' for the Path property, so I think that tells me I have everything defined correctly.

如果我将这行程序代码添加到 refresh() 方法的后面:

If I add this line of procedural code behind to the refresh() method:

numItemsLabel.Content = photos.Count

然后正确显示计数.

但我没有在 XAML 中获得绑定以显示 Photos.Count.

But I'm not getting the binding in XAML to display Photos.Count.

推荐答案

这将创建 Photos 类的新实例:

<local:Photos x:Key="Photos"/>

如果您想绑定到您在 MainWindow.xaml.vb 文件中创建的 Photos 集合,您应该将其公开为公共属性 - 您只能绑定到属性,而不能绑定到字段 - 并将窗口的 DataContext 设置为定义此属性的类的实例,即您的情况下的窗口类本身:

If you want to bind to the Photos collection that you have created in your MainWindow.xaml.vb file you should expose it as a public property - you can only bind to properties but not fields - and set the DataContext of the window to an instance of the class where this property is defined, i.e. the window class itself in your case:

Class MainWindow
    Public Property Photos As Photos

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        DataContext = Me
        ...
    End Sub
End Class

您可以绑定直接到属性:

<Label x:Name="numItemsLabel" Background="AliceBlue" FontSize="8" Content="{Binding Path=Photos.Count}"/>

这篇关于WPF 与 .NET 对象的绑定不传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆