2011-03-31 2 views
0

ListBox를 어떻게 dinamically 채울 수 있는지 알고 싶었습니다. 하지만 커스텀 클래스는 필요 없어요. 그냥 일반 셀렉터가 필요합니다.ListBoxItem 내용 채우기

나는 보통 내 자신의 클래스와 같은 것을 할 : 나도 몰라 무엇

<ListBox Name="itemList" SelectionChanged="itemList_SelectionChanged"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <TextBlock Text="{Binding title}"/> 
       <TextBlock Text="{Binding subtitle}" /> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

단순히 간단한 일을 생성하는 방법입니다 : 뭔가를 같이 :

<ListBox> 
    <ListBoxItem Name="item1" Content="First item" /> 
    <ListBoxItem Name="item2" Content="Second item" /> 
    <ListBoxItem Name="item3" Content="Third item" /> 
</ListBox> 

당신 수 구조의 예를 들어 주시겠습니까? 내가 DataTemplate을 또는 무엇을 사용하는 경우 나는

당신에게 감사 모르겠어 ...

[편집 : 나는 필요에 추가 Name 속성]

답변

2

당신은 단지와 컬렉션을 설정해야 아이템을 DataContext에 저장하고 ListBox.ItemsSource로 설정하십시오. 그러면 DataTemplate이 채워집니다.

예를 들어, 참조 :

<Grid> 
    <Grid.Resources> 
     <src:Customers x:Key="customers"/> 
    </Grid.Resources> 
    <ListBox ItemsSource="{StaticResource customers}" Width="250" Margin="0,5,0,10" 
     DisplayMemberPath="LastName"/> 
</Grid> 

과 :

public class Customer 
{ 
    public String FirstName { get; set; } 
    public String LastName { get; set; } 
    public String Address { get; set; } 

    public Customer(String firstName, String lastName, String address) 
    { 
     this.FirstName = firstName; 
     this.LastName = lastName; 
     this.Address = address; 
    } 

} 

public class Customers : ObservableCollection<Customer> 
{ 
    public Customers() 
    { 
     Add(new Customer("Michael", "Anderberg", 
       "12 North Third Street, Apartment 45")); 
     Add(new Customer("Chris", "Ashton", 
       "34 West Fifth Street, Apartment 67")); 
     Add(new Customer("Cassie", "Hicks", 
       "56 East Seventh Street, Apartment 89")); 
     Add(new Customer("Guido", "Pica", 
       "78 South Ninth Street, Apartment 10")); 
    } 

} 

예 출처 : http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemssource(v=vs.95).aspx

편집 : 코멘트에 대한 논의에 따라, 어쩌면 당신은 간단한 ItemsControl에 필요 (선택한 항목을 유지할 필요가 없거나 여러 선택을 처리하는 것이 더 좋기 때문에 ListBox의 용도로 사용할 수 있습니다.

예를 들어

:

<ItemsControl ItemsSource="{Binding NavigateItems}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Button Content="{Binding Label}" 
        Command="{Binding ButtonCommand}"                
        CommandParameter="{Binding URL}"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

그리고 : 당신은 어떻게 설정하고에

public class NavigateItem 
{ 
    public String Label { get; set; } 
    public String URL { get; set; } 

    public NavigateItem(String label, String url) 
    { 
     this.Label = label; 
     this.URL = url; 
    } 

} 

public class NavigateItems : ObservableCollection<NavigateItem> 
{ 
    public NavigateItems() 
    { 
     Add(new NavigateItem("Google", "http://www.google.com"); 
     Add(new NavigateItem("Bing", "http://www.bing.com"); 
    } 
} 

그리고 물론

은 매개 변수에 전달 된 URL로 이동합니다 ButtonCommand를 설정,하지만 달려있다 ViewModel/바인딩 위로.

+0

나는 그렇게 간단한 해결책을 찾는다. 글쎄, ListBoxItems의 name 속성을 설정하려고한다는 것을 잊어 버렸습니다. 나는 listitem 컬렉션을 준비하고리스트 박스에 바인딩하는 것과 같은 것을 할 수 있다고 생각했다. 이것이 가능한가? – enkara

+0

왜 이름 속성을 설정 하시겠습니까? 나중에 그 핸들로 접근하고 싶을 것 같아? – dain

+0

네, 아마도 저는 완전히 잘못된 길을 가고 있습니다 ... 전형적인 셀렉터 (예를 들어 도시들)를 원하지만 이것은 역동적이어야합니다. XML을 파싱하여리스트를 얻고 있습니다. 이 선택은 이벤트를 발생시킵니다. – enkara

1

사용자 지정 클래스가 없거나 원하는 경우 (예 : 문자열 컬렉션이있는 경우), 해당 문자열 컬렉션 (List, IEnumerable, string [] 등)을 ItemsSource 코드 숨김에있는 ListBox (또는 XAML에서 바인딩)에 대해 TextBlock을 사용하여 각각의 내용을 각 ListBoxItem 내에 렌더링합니다.

+0

미안 해요 이름 속성을 설정해야한다는 것을 잊었습니다. – enkara

관련 문제