【发布时间】:2017-02-17 15:59:05
【问题描述】:
我有两个列表框,它们都绑定到两个不同的 XML 文件。 目的是将 XmlElements 从一个文件拖到另一个文件(ListBox)中。
当我从一个已填充的 ListBox 拖动到另一个已填充的 ListBox 时,目标 ListBox 中的代码相当简单。 但是当目标 ListBox 为空时,由于 ListBox 不包含任何项,因此很难获取任何 XmlElements。
由于未填充目标,因此代码将在以下位置失败:
XmlElement targetXmlElement = (XmlElement)parent.Items.GetItemAt(0);
所以问题是:
如何从 ListBox-target 中获取 XmlDataProvider 或 XmlDocument:ListBox parent = (ListBox)sender;
另一个问题是目标列表框应该包含一个子节点列表,即我们拖动元素的目标。 如何访问父元素?
ListBox dragSource = null;
private void FoodListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListBox parent = (ListBox)sender;
dragSource = parent;
object data = GetDataFromListBox(dragSource, e.GetPosition(parent));
if (data != null)
{
DragDrop.DoDragDrop(parent, data, DragDropEffects.Copy);
}
}
#region GetDataFromListBox(Listbox, Point)
private static object GetDataFromListBox(ListBox source, Point point)
{
UIElement element = source.InputHitTest(point) as UIElement;
if(element != null)
{
object data = DependencyProperty.UnsetValue;
while(data == DependencyProperty.UnsetValue)
{
data = source.ItemContainerGenerator.ItemFromContainer(element);
if (data == DependencyProperty.UnsetValue)
{
element = VisualTreeHelper.GetParent(element) as UIElement;
}
if (element == source)
{
return null;
}
}
if(data != DependencyProperty.UnsetValue)
{
return data;
}
}
return null;
}
#endregion
//This listbox is bound to Dataprovider2, Objects dragged into will access the XML target
private void ListBox_Drop(object sender, DragEventArgs e)
{
ListBox parent = (ListBox)sender;
//Get access to the element from the source XML
XmlElement sourceXmlElement = (XmlElement)e.Data.GetData(typeof(XmlElement));
//Get the position of the parent to any Element in the the target list (e.g the zero element)
XmlElement targetXmlElement = (XmlElement)parent.Items.GetItemAt(0);
AppendXmlNode(sourceXmlElement, targetXmlElement);
}
【问题讨论】:
-
listbox-target 使用 Xpath="/recipelist/recipe[contains(.,'name')]/foodlist/foodtype" 过滤,这意味着 foodlist 为空,xpath 不返回任何内容跨度>
标签: c# xml wpf listbox xmldocument