我正在尝试编写一个对一些无符号长值进行解码的应用程序。每个值的格式在XML中表示为:
<Project Name="Project1">
<Message Name="a">
<BitField high="31" low="28">
<value>0001</value>
<value>1010</value>
</Bitfield>
<BitField high="27" low="17">
<value>000111101</value>
</BitField>
<BitField high="16" low="0">100h</BitField>
</Message>
</Project>
现在,项目值将显示在组合框中。当用户在组合框中选择一个值时,消息类型必须显示在列表框中。然后,当用户在列表框中选择消息类型时,必须显示位字段及其可容纳的值。现在,当用户为每个位字段选择一个值时,最终的dword值必须显示在文本框中。
我遇到过解析完整xml但与选择不相关的示例。需要你们的帮助。
另一件事是用户可以在文本框中输入双字值。现在我该如何反向解码文本框中的dword并使用上述UI显示相应的message + value?
更新:现在我已经完成了显示项目值的组合框和显示消息的列表框之间的绑定。我要做的下一件事是,当用户在列表框中选择一条消息时,位域必须显示为具有“高”,“低”,“值/ @名称”(此处未显示)的行,然后值(绑定到值/ @名称)作为列。值/ @名称必须显示为组合框。我确定我可以在dataGrid中执行此操作,但是我使用.net 3.5进行搜索,因此请在此处搜索替代方法。此外,如果xml中不存在节点,则值文本块也必须是可编辑的。最后,我将“值”列中的条目打包到DWORD中。我可以在没有数据网格的XAML中执行此操作吗? .NET 3.5的datagrid的替代品是什么?
最佳答案
这里有两个不同的问题-一个XML解析问题和一个转换问题。
为了使绑定生效,您需要将XML解析为一个代表其值的类。对于转换问题,我指出了TypeConverters的概念,该概念非常容易使用。对于XML解析问题,我想强调一下LINQ-to-XML,我认为这是屈膝的。它的几行内容甚至可以重构XML源中最复杂的对象图。对于您的Project / Message / BitField示例,我已经部分实现了一种解决方案,该解决方案将为您提供模式。
请注意“ LoadFromXml”方法。这使用linq-to-xml表达式填充对象图。此查询在您的XML源中更改的一件事是,它希望集合节点(即或)被集合节点(即)包围
public class Project
{
public string Name { get; set; }
public List<Message> MessageCollection = new List<Message>();
public void LoadFromXml(string xmlString)
{
// From System.Xml.Linq
XDocument xDocument = XDocument.Parse(xmlString);
// The following assumes your XML is well formed, is not missing attributes and has no type conversion problems. In
// other words, there is (almost) zero error checking.
if (xDocument.Document != null)
{
XElement projectElement = xDocument.Element("Project");
if (projectElement != null)
{
Name = projectElement.Attribute("Name") == null ? "Untitled Project" : projectElement.Attribute("Name").Value;
MessageCollection = new List<Message>
(from message in xDocument.Element("Project").Elements("Messages")
select new Message()
{
Name = message.Attribute("Name").Value,
BitfieldCollection = new List<BitField>
(from bitField in message.Elements("Bitfields")
select new BitField() {High = int.Parse(bitField.Attribute("High").Value), Low = int.Parse(bitField.Attribute("Low").Value)})
}
);
}
}
}
}
public class Message
{
public string Name { get; set; }
public List<BitField> BitfieldCollection = new List<BitField>();
}
public class BitField
{
public int High { get; set; }
public int Low { get; set; }
public List<string> ValueCollection = new List<string>();
}
关于c# - WPF中的XML数据绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3385642/