2012-02-07 41 views
0

到用戶控件我如何可以爲用戶控件指定數據源:指定綁定源列表框中

<ScrollViewer VerticalScrollBarVisibility="Visible" VerticalAlignment="Stretch"> 
    <ListBox ItemsSource="{Binding}">         
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <local:ucMyControl /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</ScrollViewer> 

如何ucMyControl知道什麼值取?我意識到,lisbox會創建儘可能多的ucMyControls,因爲有那些在bondong集合中的項目嗎? 此外,scrollviewers不工作 - 我無法達到第三控制(無論如何他們都是空的,但我希望你會給我帶領如何綁定它)。

回答

0

是從一個ItemTemplateItemsControls(例如ListBox)實例化所述的控制有其DataContext屬性自動地從ItemsItemsSource收集的ItemsControl的設置爲適當項目。

所以,如果你具有例如Person對象具有屬性FirstNameLastName爲列表框項目的集合,你可以綁定像這樣在你的用戶控件:

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

你並不需要明確設置DataContext屬性。

+0

我爲什麼要指定TextBlocks - 我已經有用戶控件和我需要的控件和佈局? – Nickolodeon 2012-02-07 14:50:15

+0

是的,但我怎麼知道這一點。這只是如何綁定的一個例子。 – Clemens 2012-02-07 15:04:13

+0

然後我怎樣才能綁定到usercontrol呢? – Nickolodeon 2012-02-07 15:37:47