0

试图将 a 绑定listbox到一个对象。代码运行没有错误,但由于某种原因示例数据没有出现在listbox

XAML:ucDataBindingObject.xaml

<UserControl x:Class="TheProject.UserControls.ucDataBindingObject"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             Name="DataBindingObject"
             Width="Auto"
             Height="Auto"
             mc:Ignorable="d">

    <Grid Width="130"
          Height="240"
          Margin="0">

        <ListBox Name="lbObject"
                 Width="110"
                 Height="80"
                 Margin="10,7,-9.6,0"
                 HorizontalAlignment="Left"
                 VerticalAlignment="Top"
                 DisplayMemberPath="Name"
                 ItemsSource="{Binding ElementName=ucDataBindingObject,
                                       Path=Clients}" />

    </Grid>
</UserControl>

C#:ucDataBindingObject.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
namespace TheProject.UserControls
{
    public partial class ucDataBindingObject : UserControl
    {

        public List<Client> Clients { get; set; }


        public ucDataBindingObject()
        {
            Clients = new List<Client>();
            Clients.Add(new Client(1, "David")); // sample data
            Clients.Add(new Client(2, "Helen"));
            Clients.Add(new Client(3, "Joe"));


            InitializeComponent();
        }
    }

C#Client.cs

using System;
using System.Linq;

namespace TheProject.UserControls
{
    public class Client
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public Client(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }
    }
}
4

1 回答 1

3

将您的 ItemsSource 绑定更新为

ItemsSource="{Binding Path=Clients}" 

并在视图的构造函数中,在 InitializeComponents 之后将其 DataContext 设置为

this.DataContext = this;

没有名为 ucDataBindingObject 的元素,它是您的用户控件的类名

或将绑定中的元素名称更改为您命名为用户控件的 DataBindingObject

于 2013-09-28T19:49:01.843 回答