开发者

reading xaml files with XDocument

开发者 https://www.devze.com 2023-03-16 08:34 出处:网络
I have the following silverlight sample data xaml file, which works perfect in design mode: <viewmodel:MapViewModel

I have the following silverlight sample data xaml file, which works perfect in design mode:

<viewmodel:MapViewModel 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
xmlns:x="http://schemas.microso开发者_如何学Cft.com/winfx/2006/xaml"
xmlns:viewmodel="clr-namespace:MyApplication.ViewModels">
<viewmodel:MapViewModel.Lines>
    <viewmodel:Line Line="M 100 100 L 280 100 S 302 102 315 115 L 500 300"/>
</viewmodel:MapViewModel.Lines></viewmodel:MapViewModel>

Since this data is also useful during runtime (may be not for ever), I want to read the xml within code behind. Therefor I use XDocument and it works, means I can read and parse the whole document. But I cannot figure out, how to access the elements. Hoe do I acces a "Line"?

What I've tried is:

            var lines = doc.Descendants(XName.Get("Line", "viewmodel:")).ToArray();

It allways returns nothing. Since I assumed it is a problem of the namespace, I've tried

  • "viewmodel"
  • "viewmodel:"
  • "MyApplication.ViewModels"
  • "MyApplication.ViewModels:"
  • "clr-namespace:MyApplication.ViewModels" and
  • "clr-namespace:MyApplication.ViewModels:"

Can someone tell me what I'm making wrong? Is the missing xml-header the reason? I read an xml-file with a correct header (but without a namespace) allready and it worked.


use an XNamespace:

var xdoc = XDocument.Parse(xaml);
XNamespace ns = "clr-namespace:MyApplication.ViewModels";
var lines = xdoc.Descendants(ns + "Line").ToArray();

you can also use this syntax:

var lines = xdoc.Descendants("{clr-namespace:MyApplication.ViewModels}Line").ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消