首页 > 解决方案 > 列表框项目内的 ComboBox 的龚 WPF 问题

问题描述

您好,我正在使用Gong WPFItems在 ListBox 内重新排序

<Window x:Class="ComboBoxIssue.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ComboBoxIssue"
    xmlns:dd="urn:gong-wpf-dragdrop"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<ListBox 
    dd:DragDrop.IsDragSource="True"
    dd:DragDrop.IsDropTarget="True"
    ItemsSource="{Binding Layers}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:UserControl1/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

GongWpf 提供AttachedProperties在 ListBox 中启用拖放功能:

dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True"

ListBoxItemSource绑定到Layermain 中的 ObservableCollection ViewModel

public class ViewModel
{
    public ViewModel()
    {
        Layers = new ObservableCollection<Layer> { new Layer(), new Layer(), new Layer(), new Layer() };
    }
    public ObservableCollection<Layer> Layers { get; }
}

现在 Layer 只是一个用于显示问题的空类:

public class Layer
{

}

UserControlused as包含DataTemplate一个:ComboBox

<ComboBox Height="25" Width="100">
    <ComboBoxItem>HELLO</ComboBoxItem>
    <ComboBoxItem>BONJOUR</ComboBoxItem>
    <ComboBoxItem>NIHAO</ComboBoxItem>
</ComboBox>

现在,当我在 中使用拖放重新排序项目时ListBox,已放置的项目ComboBox SelectedItem不再可见。

为什么 ?

谢谢

标签: c#wpfcombobox

解决方案


为什么 ?

因为您还没有将它绑定到Layer类的源属性。如果添加诸如属性:

public class Layer
{
    private string _selectedItem;
    public string SelectedItem
    {
        get => _selectedItem;
        set => _selectedItem = value;
    }
}

...并将 the 的SelectedItem属性绑定ComboBox到它:

<ListBox 
    dd:DragDrop.IsDragSource="True"
    dd:DragDrop.IsDropTarget="True"
    ItemsSource="{Binding Layers}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ComboBox Height="25" Width="100" SelectedItem="{Binding SelectedItem}"
                      xmlns:s="clr-namespace:System;assembly=mscorlib">
                <s:String>HELLO</s:String>
                <s:String>BONJOUR</s:String>
                <s:String>NIHAO</s:String>
            </ComboBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

...它对我来说很好。


推荐阅读