数据绑定类中的列表 [英] Data Binding a List in a Class

查看:83
本文介绍了数据绑定类中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我个人认为WPF数据绑定根本不那么容易.我有
上下反复地研究它,然后在星期二整天研究它.我尝试过实验
绑定如下.
我有一个Person对象列表.
Person具有Name属性和一个KIDs LIST属性,KID具有Name属性.
我希望ListBox项能够扩展.
扩展器头绑定到personList人员名称. (没问题).
扩展器内的TextBlock绑定到KID.name. (问题).

我已经尝试了Heirachical数据模板等,等等.
通过复制示例取得了一些成功,但我似乎无法做到
掌握此数据绑定.我可以看一下
其中一个例子 拥有明确了解的您可以在XAML中进行此操作.
后面的代码中已经存在人员列表的实例.

p.s.
当数据实际上出现在某物上时,我会非常退出.

I personally do not find WPF Data Binding to be easy at all. I have
studied it up and down and then all day on tuesday. I tried experiments
to Bind as Follows.
I have a List of Person objects.
Person has Name property and a LIST of KIDs property , KID has Name property.
I Want ListBox Items to be expanders.
expander header is Bound to personList person name. ( no problem ).
TextBlock inside expander Bound to KID.name. ( problem ) .

I have attempted Heirachical Data Templates etc etc etc.
While I have met with some success by copying examples , I cannot seem
to master this Data Binding. So Can I see an example of how one of
You who have clear understanding would do this in XAML.
Instance of person list already exists in code behind.

p.s.
I get very exited when data actually appears on somthing.

推荐答案

好了,将扩展器用于列表框项目并不是一个好方法.
您需要使用的是 TreeView 而不是列表框.

尝试使用TreeView.在Google上搜索如何在树状视图中进行数据绑定并了解每个步骤.
我同意在WPF中进行绑定不是那么容易,但也并不困难!
自从我学习WPF已经2个月了,我学到了很多东西!
尝试读几本书.
我的最爱是:
Windows演示基础由Adam Nathan释放
并使用.net 3.5签出Appress的Pro WPF.

我研究了他们,发现它非常有帮助!因此,请重新开始!

我发现了一些可能对您有很大帮助的链接:
下面的这个使用Expander(正是您想要的!)

http://blogs.msdn.com/b/chkoenig/archive/2008/05/24/hierarchical-databinding-in-wpf.aspx

http://social.msdn.microsoft.com/论坛/zh-CN/wpf/thread/32a6e3c3-2ea9-43c9-b91f-282edf48b1aa

这是一个简单的示例:

http://www.mattlong.com.au/?p=37

希望对您有所帮助!
Well using expanders for listbox items is not a good technique.
What you need to use is a TreeView not a listbox.

Try using TreeView. Search google on how to do data binding in a Tree view and understand each and every step.
I agree that binding in WPF is not that easy but its not difficult also!
Its been 2 months since i am learning WPF and i have learnt a lot!
Try to read a few books.
My favourites are:
Windows Presentation Foundation Unleashed by Adam Nathan
and check out Appress''s Pro WPF with .net 3.5

i studied them and i found it to be very helpful! so go ahead give a fresh start!

i found a few links that might be a great help for you:
this one below uses Expander(exactly what you want!)

http://blogs.msdn.com/b/chkoenig/archive/2008/05/24/hierarchical-databinding-in-wpf.aspx

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/32a6e3c3-2ea9-43c9-b91f-282edf48b1aa

This one is a simple example:

http://www.mattlong.com.au/?p=37

Hope it helps!


这是一个可能的答案!

我的课程:

Here is a possible answer!

My Classes:

Imports System.Collections.ObjectModel

Public Class Person

    Dim mname As String
    Dim mkids As New ObservableCollection(Of Kid)

    Public Property PName() As String
        Get
            Return mname
        End Get
        Set(ByVal value As String)
            mname = value
        End Set
    End Property

    Public Property Kids() As ObservableCollection(Of Kid)
        Get
            Return mkids
        End Get
        Set(ByVal value As ObservableCollection(Of Kid))
            mkids = value
        End Set
    End Property

    Public Sub New(ByVal _nm As String, ByVal _kids As ObservableCollection(Of Kid))
        mname = _nm
        mkids = _kids
    End Sub

End Class

Public Class Kid

    Dim mkname As String

    Public Property KName() As String
        Get
            Return mkname
        End Get
        Set(ByVal value As String)
            mkname = value
        End Set
    End Property

    Public Sub New(ByVal _kname As String)
        mkname = _kname
    End Sub

End Class


上面的类有一个构造函数来加载值,就像您将看到我如何使用它一样.

我的window_loaded事件:


The above class has a Constructor to load values as you will see down how i have used it.

My window_loaded event:

Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    Dim perList As New ObservableCollection(Of Person)

    Dim kidList1 As New ObservableCollection(Of Kid)
    kidList1.Add(New Kid("AAA"))
    kidList1.Add(New Kid("BBB"))
    perList.Add(New Person("Person 1", kidList1))

    Dim kidList2 As New ObservableCollection(Of Kid)
    kidList2.Add(New Kid("CCC"))
    kidList2.Add(New Kid("DDD"))
    perList.Add(New Person("Person 2", kidList2))

    ListBox1.ItemsSource = perList

End Sub



因此,我创建了一个孩子集合,但没有为每个孩子创建对象.

项目模板:



So i have created a collection of kids without creating objects for each kid.

Item template:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Expander Name="myExpander" ExpandDirection="Right">
            <Expander.Header>
                <TextBlock Text="{Binding Path=PName}"/>
            </Expander.Header>
            <Expander.Content>
                <TextBlock Text="{Binding Path=Kids, Converter={StaticResource MyConv}}"/>
            </Expander.Content>
        </Expander>
    </DataTemplate>
</ListBox.ItemTemplat


e>

我创建了一个Value Converter类,将孩子的集合转换为字符串,以便textblock可以获取该字符串.

转换器类:


e>

I have created a Value Converter class to convert the collection of kids to string, so the textblock can get that string.

Converter Class:

Imports System.Collections.ObjectModel
Public Class MyValueConverter
    Implements IValueConverter

'Convert function which takes values from list and uses casting to get the Kid class object myKid and assign it to the string myKids.

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

'The value contains the Collection of kids from the property defined in 
 the property of person class
        Dim myList As ObservableCollection(Of Kid) = value
        Dim myKids As String = String.Empty
        Dim myKid As Kid
        For i As Integer = 0 To myList.Count - 1
            myKid = TryCast(myList.Item(i), Kid) ' Get the Kid object
            myKids = myKids & myKid.KName & " "
        Next
        Return myKids
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException("Convert Back not implemented")
    End Function
End Class



因此,上面的代码通过检索集合中孩子的名字来返回字符串.

xaml应该识别此类,因此我们必须提供当前程序集的名称空间:



So the above code returns a string by retrieving the kid''s name in the collection.

The xaml should recognize this class so we have to provide a namespace of the current assembly:

xmlns:local="clr-namespace:ListBoxWithExpander"



并在window.resources中提供一个密钥,以在textblock中使用转换器!:



and provide a key in window.resources to use the converter in textblock!:

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


>
因此,我们将把密钥用作静态资源,并在文本块中分配它!
而已!! :-D PHEW!

很抱歉,代码在VB中,但我认为转换不会有任何问题.
U可以使用它来转换: http://www.developerfusion.com/tools/convert/vb- to-csharp/ [ ^ ]

现在应该可以正常工作了! :thumbsup:


>
So the we will use the key as static resource and assign it in the textblock!!

That''s it!! :-D PHEW!

And sorry that the code is in VB but i think there won''t be any problem in converting.
U can use this to convert: http://www.developerfusion.com/tools/convert/vb-to-csharp/[^]

Now it should work fine! :thumbsup:


您好!
为了完全解决您的问题,如果您可以向您展示所使用的类,那就太好了.

这是我的做法:

人员班

Hi there!
To completely solve your question, it would be great if you can show the class that you are using.

Here is how i did:

Person Class

Public Class Person

    Private myname As String
    Private myage As Integer

    Public Property Name() As String
        Get
            Return myname
        End Get
        Set(ByVal value As String)
            myname = value
        End Set
    End Property

    Public Property Age() As Integer
        Get
            Return myage
        End Get
        Set(ByVal value As Integer)
            myage = value
        End Set
    End Property

    Public Sub New(ByVal myn As String, ByVal mya As Integer)
        myname = myn
        myage = mya
    End Sub

End Class



现在在window_loaded事件中,
写这个:



Now in the window_loaded event,
write this:

Dim myoList As New ObservableCollection(Of Person)
myoList.Add(New Person("Tarun Kumar", 21))
myoList.Add(New Person("Bhupesh Kumar", 17))
ListBox2.ItemsSource = myoList




提示,请使用observablecollection而不是list,因为它已针对WPF进行了优化.

现在,您需要与控件模板一起创建样式,以使列表框项目具有新外观:
ListBoxItem的样式




As a tip, use observablecollection instead of list because it is optimized for WPF.

Now you need to create a style together with a control template to give a new look to your listbox items:
Style for ListBoxItem

<Style x:Key="TryExp" TargetType="ListBoxItem">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Expander Header="{Binding Path=Name}" Margin="3" ExpandDirection="Right" BorderThickness="1" BorderBrush="LightBlue">
                    <!--<ContentPresenter Content="{Binding Path=Age}"/>-->
                    <TextBlock Text="{Binding Path=Age}"/>
                </Expander>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>





并在用于ListBox的xaml中,添加以下内容:





and in the xaml for ListBox, add this:

<ListBox ItemContainerStyle="{DynamicResource TryExp}" Margin="0,0,61,46" Name="ListBox2" Height="105" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="151" >
</ListBox


>

现在应该可以正常工作了! :)


>

now it should work smoothly! :)


这篇关于数据绑定类中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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