当前位置: 动力学知识库 > 问答 > 编程问答 >

wpf - specifying binding source to usercontrol in listbox

问题描述:

How can I specify datasource for a user control:

<ScrollViewer VerticalScrollBarVisibility="Visible" VerticalAlignment="Stretch">

<ListBox ItemsSource="{Binding}">

<ListBox.ItemTemplate>

<DataTemplate>

<local:ucMyControl />

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</ScrollViewer>

How ucMyControl know what values to take? I realize that lisbox will create as many ucMyControls as there are items in bondong collection?

Also, scrollviewers don't work - I can't get to 3rd control (they are all empty anyway, but I hope you'll give me leads how to bind it).

网友答案:

The control that is instantiated from an ItemTemplate in an ItemsControls (e.g. ListBox) has its DataContext property automatically set to the appropriate item from the Items or ItemsSource collection of the ItemsControl.

So if you for example have a collection of Person objects with properties FirstName and LastName as ListBox items you can bind like this in your UserControl:

<UserControl ...>
    <StackPanel>
        <TextBlock Text="{Binding Path=FirstName}"/>
        <TextBlock Text="{Binding Path=LastName}"/>
    </StackPanel>
</UserControl>

You do not need to set the DataContext property explicitly.

分享给朋友:
您可能感兴趣的文章:
随机阅读: