2012-08-08 32 views
1

我似乎無法弄清楚爲什麼列表框項目放在彼此的頂部......他們應該在另一個之下。這裏有一些標記和代碼。列表框項目被放置在彼此頂部

<ListBox x:Name="DeviceList" Background="#ff4c4c4c" BorderThickness="0" ScrollViewer.CanContentScroll="False" MouseEnter="DeviceList_MouseEnter" MouseLeave="DeviceList_MouseLeave" 
        ManipulationBoundaryFeedback="DeviceList_ManipulationBoundaryFeedback" ItemContainerStyle="{DynamicResource ResourceKey=ListBoxItemStyle}" PreviewMouseDown="DeviceList_PreviewMouseDown" 
        PreviewMouseMove="DeviceList_PreviewMouseMove" PreviewMouseUp="DeviceList_PreviewMouseUp" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" DockPanel.Dock="Bottom"> 
       <ListBox.Resources> 
        <ResourceDictionary> 
         <ResourceDictionary.MergedDictionaries> 
          <ResourceDictionary Source="..\Utilities\Resources\Themes\Slider.xaml"></ResourceDictionary> 
         </ResourceDictionary.MergedDictionaries> 
        </ResourceDictionary> 
       </ListBox.Resources> 
      </ListBox> 

#region Constructors 
    /// <summary> 
    /// Constructor. 
    /// </summary> 
    public ConfiguratorView() 
    { 
     InitializeComponent(); 

     foreach (Device device in (Application.Current.Windows[1].DataContext as ConfiguratorViewModel).AvailableDevices) 
     { 
      devices.Add(AddDevice(device.Icon + "_def", device.Description)); 
     } 

     DeviceList.ItemsSource = devices; 
    } 
    #endregion 


    #region Internal Members 
    /// <summary> 
    /// Add the device to the list of devices. 
    /// </summary> 
    /// <param name="icon"></param> 
    /// <param name="description"></param> 
    /// <returns></returns> 
    private Canvas AddDevice(string icon, string description) 
    { 
     Canvas canvas = new Canvas(); 
     canvas.Name = icon; 

     ContentControl backgroundContent = new ContentControl(); 
     Label label = new Label(); 

     backgroundContent.Template = Application.Current.FindResource(icon) as ControlTemplate; 
     label.Content = description; 

     canvas.Children.Add(backgroundContent); 
     canvas.Children.Add(label); 

     return canvas; 
    } 

設備列表添加帆布爲項目......然後我設置的ItemsSource到列表中。加載它顯示在最後一個圖標上的所有圖標。有什麼想法嗎?

+0

很難準確地告訴你在顯示的代碼片段中做了什麼,但'Canvas'es是用絕對定位呈現的,這可能是問題的根源...... – 2012-08-08 21:24:10

回答

1

由於Canvas.Top默認爲NaN,因此所有內容都會出現在對方之上。

您可以手動計算出合適的Canvas.Top值,但我建議:

  1. 保持設備對象的簡單與描述和圖標

  2. 創建爲ListBox一個DataTemplate屬性項目來顯示這些屬性。

編輯:

例如(我沒有測試過這一點)

說你的設備類看起來是這樣的:

public class Device 
{ 
    public string Description { get; set; } 
    public object Icon { get; set; } 
} 

然後你datatemplete爲ListBox可能看起來像這樣:

<ListBox ItemsSource="{Binding Devices}"> 
    <ListBox.ItemsTemplate> 
     <DataTemplate> 
      <Canvas> 
       <!-- add items here --> 
       <TextBlock Text="{Binding Description}" Canvas.Top="5" /> 
      <Canvas> 
     </DataTemplate> 
    </ListBox.ItemsTemplate> 
</ListBox>