정확히 ListBox
및 ItemsControl
컨트롤이 생성 된 것입니다. ListBox는 ItemsControl의 향상된 버전이므로, 후자의 기본 컨트롤에 대해서만 설명하겠습니다.
ItemsControl
에는 ItemsSource
이라는 종속성 속성이 있습니다. 거기에 컬렉션을 전달하면 ItemsControl은 해당 소스에서 가져온 항목의 "보기"로 채워진 "패널"을 생성합니다.
기본적으로 ItemsControl은 StackPanel을 패널로 사용하지만 ItemPanel
속성으로 원하는 경우 변경할 수 있습니다.
기본적으로 ItemsControl은 기본 WPF 템플릿 일치를 사용하여 각 항목에 대한보기를 생성하고 표시합니다. 그러나 구체적으로 ItemTemplate
속성을 사용하여보기 모양을 알려주는 DataTemplate
을 설정할 수 있습니다.
예 :
<!-- simple vertical/StackPanel list -->
<ItemsControl ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<!-- the template of a single Item -->
<!-- note that I'm setting it here explicitely -->
<!-- but the ItemTemplate prop could have been bound, resourcized, etc -->
<DataTemplate>
<Border BorderThickness="1">
<!-- reads a ShoeSize from the items from MyItems -->
<TextBlock Text="{Binding ShoeSize}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- simple horizontal/StackPanel list -->
<ItemsControl ItemsSource="{Binding MyItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1">
<TextBlock Text="{Binding ShoeSize}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- you can use any panel and any itemtemplate -->
<ItemsControl ItemsSource="{Binding MyXYPoints}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!-- any Panel is OK! even plain canvas -->
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- just remember that in canvas there's no autolayout -->
<!-- so you need to set the coords on each item! -->
<Ellipse Width="2" Height="2"
Canvas.Left="{Binding PositionX}"
Canvas.Top="{Binding PositionY}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ListBox
가 본질적으로 동일한 제어하지만, 너무 많은이있는 경우 (가상화) 항목을 스크롤 할 수있는 능력과 같은 몇 가지 '기본'케이크를 제공, 항목을 선택 등등. ItemsControl에서 이러한 기능을 사용할 수 있지만 직접 구현하거나 최소한 구성해야합니다. ListBox는 이미 완료되었습니다. 그러나 ItemsControl보다 확실히 "무거운"것이므로 가장 적합한 것을 선택하십시오.
어쨌든 .. 내가 지금 같은 분위기에 있었기 때문에 나는 그것을 썼다. 그러나 ItemsControl과 Bindings에 대해 더 많이 읽어야합니다. WPF에서는 "코드에서 수동으로"UI에 물건을 배치하지 않습니다. 전문가는 이미 그 모든 것을 다 다루었 기 때문에 실제로 쓰지 말아야합니다. this excellent series of articles by Dr.Wpf을 읽어주세요. 특히 "I"장, 당신이 묻고있는 것과 정확히 관련이 있기 때문에, 그러나 나는 정말로 그것을 모두 읽는 것을 권장합니다. 다소 자세히 설명되어 있지만 일부 독자에게는 다소 지나치게 많이 쓰이지 만 손에 가지고있는 훌륭한 도구에 대한 개요가 많이 필요합니다.
http://adackoverflow.com/questions/11095189/adding-controls-dynamically-in-wpf-mvvm/11095460#11095460 – blindmeis
왜 목록 및 항목 템플릿을 사용하지 않습니까? –