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 设置为列表。加载它会在最后一个图标的顶部显示所有图标。有什么想法吗?

4

1 回答 1

1

因为 Canvas.Top 默认为 NaN,所以一切都将出现在彼此之上。

您可以手动计算适当的 Canvas.Top 值,但我建议:

  1. 使用描述和图标的属性使设备对象保持简单

  2. 为 ListBox 项创建一个DataTemplate以显示这些属性。

编辑:

例如(我没有测试过这个)

假设您的设备类看起来像这样:

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

然后 ListBox 的数据模板可能如下所示:

<ListBox ItemsSource="{Binding Devices}">
    <ListBox.ItemsTemplate>
        <DataTemplate>
            <Canvas>
                <!-- add items here -->
                <TextBlock Text="{Binding Description}" Canvas.Top="5" />
            <Canvas>
        </DataTemplate>
    </ListBox.ItemsTemplate>
</ListBox>
于 2012-08-08T21:28:23.380 回答