Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C代码隐藏中的数据绑定#_C#_Wpf_Data Binding - Fatal编程技术网

C# C代码隐藏中的数据绑定#

C# C代码隐藏中的数据绑定#,c#,wpf,data-binding,C#,Wpf,Data Binding,我有一个很简单的问题: 我有一个类型为List的People属性,一个人有名字和姓氏。 我想在我的listBoxPerson上显示名称,我想在代码隐藏中进行绑定操作-不想使用ItemsSource属性- 以下是我的代码片段: Binding userBinding = new Binding(); userBinding.Source =People; userBinding.Path = new PropertyPath("Person.Name");

我有一个很简单的问题:

我有一个类型为List的People属性,一个人有名字和姓氏。 我想在我的listBoxPerson上显示名称,我想在代码隐藏中进行绑定操作-不想使用ItemsSource属性- 以下是我的代码片段:

Binding userBinding = new Binding();
        userBinding.Source =People;
        userBinding.Path = new PropertyPath("Person.Name");
        listBoxPerson.SetBinding(ContentProperty, userBinding);
这是我的xaml代码:

 < ListBox Height="303" HorizontalAlignment="Left" Margin="12,108,0,0" Name="listBoxPerson" VerticalAlignment="Top" Width="234" >

        < ListBox.Resources >
            < ObjectDataProvider x:Key="UserData" ObjectType="local:Person"/ >
        < /ListBox.Resources >
        < ListBox.ItemTemplate >
            < DataTemplate >
                < Label Content="{Binding Path=Name}" ></Label  >
            < /DataTemplate >
        < /ListBox.ItemTemplate >
    < /ListBox >

但是没有人列出第一个给定的代码。我不知道如何解决这个绑定问题,如果有任何帮助,我会很高兴的。

您是否尝试了
项目资源属性而不是
内容属性,您可以使用它吗?

这个问题真的没有任何意义

您是否认为应该在代码中填充
ListBox.Items
,而不是将
ItemsSource
绑定到集合?如果是这样,就根本不需要创建绑定;您的代码应该如下所示:

MyListBox.Items.AddRange(myCollection);
您是否认为应该在代码中而不是在XAML中创建与
Name
属性的绑定?在这种情况下,您需要在
数据模板
中找到
标签
对象,并在其上创建绑定。很难想象在什么情况下这会是个好主意


如果有人问你“为什么这样做?”,说“因为我被告知要这样做”真的不是答案。你需要找出为什么你被要求这样做。除此之外,了解原因将有助于你理解你想问的问题。

我原以为有答案,但当ı看到这是一个编辑时,有点失望…=)
MyListBox.Items.AddRange(myCollection);