XamlServices class in .Net 4.0

 

XAML has up to now played a big role in WPF and Silverlight and is seen as a markup language to design GUIs. That is not quite true. XAML describes objects, their properties and their relations. It is not limited to designing user interfaces. That is why XAML has been separated from WPF and Silverlight in .NET framework 4.0.
 
Let's assume you have a class  BigSerializableObject and want to save it to a file with all properties and attached objects. Later, you want to be able to load it again from the file and get a new instance which is a perfect copy of the object you originally serialized. You might do this with XML. Serializing is not much of a problem. Deserializing is a completely different story. You would have to navigate through the XML nodes, create instances of the required objects, fill them with the proper values and assemble them according to the structure of the XML. That also means writing lots of code.
 
Things get far easier when using the  System.Xaml.XamlServices class. Serializing the object is very similar to what you might be used to from XML:
 
 Collapse
using (TextWriter XamlWriter = File.CreateText("Test.xaml"))
{
  System.Xaml.XamlServices.Save(XamlWriter , MyBigSerializableObject);
}
 
That's it. Your object has just been serialized to XAML into the file  Test.xaml. The only condition is that your object and all objects attached to it must be serializable.
 
Now we want to load our object again from the file  Test.xaml. If possible, we want it as an object instance, just like it was before. And we don't want to write any code which constructs the object from the file. Try this:
 
 Collapse
using (TextReader XamlReader = File.OpenText("Test.xaml"))
{
  BigSerializableObject MyNewBigSerializableObject = (BigSerializableObject)System.Xaml.XamlServices.Load(XamlReader);
}
 
Again, that was it. You now have a new instance of your original object, loaded from the file.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值