2012-02-13 11 views
3

まずステップ:シンプルなリストボックスそのコードとカスタムWPFのListBox使ってC#

<ListBox Height="95" HorizontalAlignment="Left" Margin="17,0,0,0" Name="myList" VerticalAlignment="Top" Width="287"> 

myList.Items.Add("toto"); 

[OK]を、それが正常に働いています。

第2ステップ:各行に2つの列が必要です。

だから私は

<ListBoxItem Name="my_item"> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Name="my_item_id"></TextBlock> 
     <TextBlock Name="my_item_name"></TextBlock> 
    </StackPanel> 
</ListBoxItem> 

ことしかし、私のコードで試してみましたか?

私は

my_item_id = "1234"; 
my_item_name = "toto"; 
myList.Items.Add(my_item); 

をしようとしたが、それは働いていない...私はそれを操作できるようにする方法その後、私が間違ってやっていると仮定しますが?

ありがとうございました。

+0

あなたは列がサイズ変更可能なことと、より格子状の外観を持つようにしたいとリストビューの代わりに、リストボックスを使用して考え感じる場合 – SvenG

答えて

7
  1. あなたはアイテムのpropertiesListBoxbindsからItemTemplateを割り当てる必要があります。例えば

    <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel> 
          <TextBlock Text="{Binding Id}"/> 
          <!-- ... --> 
    
  2. これらのプロパティを持つアイテムを追加します。 anonymous objects

    myList.Items.Add(new { Id = "Lorem", ... }); 
    

も参照してください:Data Templating