开发者

reading xaml files with XDocument

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜