[英]How to get data from local XML file and binded with XAML. Xamarin
I'm working on Xamarin.Android and trying to get data from local XML file and bind with XAML.我正在处理 Xamarin.Android 并尝试从本地 XML 文件中获取数据并与 Z8CBFD56579569C436DDDED1 绑定。
Problem is throw Exception("There is no store file.");
问题是throw Exception("There is no store file.");
is coming.来了。 Please help me to figure out how to fix this exception and what needs to be done to bind the XML data with the XAML.请帮我弄清楚如何修复这个异常以及需要做些什么来将 XML 数据与 XAML 绑定。
Store.xml file is located in the Root of the project. Store.xml 文件位于项目的根目录下。
Any help is appreciated.任何帮助表示赞赏。 Thanks!谢谢!
I used the following code:我使用了以下代码:
ViewModel- ViewModel-
public static void StoreLoad()
{
Dictionary<int, StoreData> newlist = new Dictionary<int, StoreData>();
XmlTextReader reader;
try
{
reader = new XmlTextReader(new FileStream(Path.Combine("store.xml"), FileMode.Open));
}
catch (FileNotFoundException ex)
{
throw new Exception("There is no store file.");
}
catch
{
throw new Exception("Unable to load store file.");
}
try
{
reader.Read();
reader.MoveToContent();
if (reader.LocalName != "StoreList")
throw new Exception("Store file is corrupt.");
reader.Read();
reader.MoveToContent();
while (!reader.EOF)
{
if (reader.LocalName == "Store")
{
int code;
string name;
string number;
int dept = 0;
code = int.Parse(reader.GetAttribute("Code"));
number = reader.GetAttribute("Number");
name = reader.GetAttribute("ShortName");
string deptStr = reader.GetAttribute("Dept");
if (deptStr != null && deptStr.Length > 0)
dept = int.Parse(deptStr);
else
// If App is not supported, set fixed at 0.
dept = 0;
newlist.Add(code, new StoreData(code, number, name, dept));
}
reader.Read();
reader.MoveToContent();
}
StoreData = newlist;
}
finally
{
reader.Close();
}
}
}
Model: Model:
public class StoreData
{
public int Code { get; set; }
public string Number { get; set; }
public int Dept { get; set; }
public string ShortName { get; set; }
}
At first, please set the file's build action as the EmbeddedResource.首先,请将文件的构建动作设置为 EmbeddedResource。 And then you can try the following code to read the content from the file.然后您可以尝试以下代码从文件中读取内容。
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Your class name)).Assembly;
Stream stream = assembly.GetManifestResourceStream("ProjectNameSpace.Room.xml");
For more information, please check the official document about Embedding in Shared Projects and there is an sample about binding the data in the xml to the controls in the xaml.有关更多信息,请查看有关Embedding in Shared Projects的官方文档,并且有一个关于将 xml 中的数据绑定到 xaml 中的控件的示例。
In addition, you can try put the file in the Assets folder and then get it's data with the dependency service.另外,您可以尝试将文件放在 Assets 文件夹中,然后通过依赖服务获取它的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.