[英]WPF XAML serialize/deserialize
我的應用程序基本上是使用一個包含其他控件的WPF Canvas並將其序列化為XML文件,然后反序列化以顯示序列化的數據或先前保存的數據。 序列化/反序列化工作正常,所有內容都保存並恢復了。 問題是,在反序列化之后,如果我嘗試使用以下代碼更改圖像源,它將不起作用:
testLogo.Source = new BitmapImage(new Uri(file.FileName));
圖像在XAML中被引用如下:
<Canvas Name="mainCanva" Margin="0,0,12,0" Width="1729" Height="150" VerticalAlignment="Top">
<Border BorderThickness="3" BorderBrush="#FF009B80" FlowDirection="LeftToRight" VerticalAlignment="Top" HorizontalAlignment="Left" Width="1729" Height="150">
<Grid Margin="0" Background="White" Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Uid="">
<Grid HorizontalAlignment="Left" Margin="3,28,0,57">
<Image HorizontalAlignment="Left" Margin="0,0,0,0" x:Name="testLogo" Stretch="UniformToFill" Width="317" Source="file:///C:/Users/logo.jpg" />
</Grid>
</Grid>
</Border>
</Canvas>
反序列化代碼如下:
Canvas canvas = DeSerializeXAML(appPath + "\\tmp\\mainCanva.xml") as Canvas;
mainCanva.Children.Clear();
while (canvas.Children.Count > 0)
{
UIElement obj = canvas.Children[0];
canvas.Children.Remove(obj);
mainCanva.Children.Add(obj); // Add to canvas
}
要注意的另一點是,在反序列化之后,我試圖找出使用Snoop發生了什么,Snoop也無法更改圖像源,盡管如果我通過拖放十字線將Snoop重新連接到應用程序,Snoop現在可以更改圖像了。資源。 “舊的” Snoop窗口可以看到從testLogo.Source =命令正在更新的圖像源。 WPF檢查器沒有此問題,它會在反序列化發生時立即進行自我更新。 我的猜測是視覺樹有問題...而且WPF可以做到,我認為可以對其進行排序。
感謝您的幫助。
根據要求的序列化/反序列化功能:
public static void SerializeToXAML(UIElement element, string filename)
{
string strXAML = System.Windows.Markup.XamlWriter.Save(element);
using (System.IO.FileStream fs = System.IO.File.Create(filename))
{
using (System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(fs))
{
streamwriter.Write(strXAML);
}
}
}
public static UIElement DeSerializeXAML(string filename)
{
using (System.IO.FileStream fs = System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
return System.Windows.Markup.XamlReader.Load(fs) as UIElement;
}
}
您需要更新變量參考。
當您調用mainCanva.Children.Clear()時,它將刪除所有子級,包括testLogo。 即使變量testLogo不再是UI的一部分,它仍將指向原始testLogo對象。
嘗試這個:
Canvas canvas = DeSerializeXAML(appPath + "\\tmp\\mainCanva.xml") as Canvas;
mainCanva.Children.Clear();
while (canvas.Children.Count > 0)
{
UIElement obj = canvas.Children[0];
canvas.Children.Remove(obj);
mainCanva.Children.Add(obj); // Add to canvas
}
testLogo = mainCanva.FindName("testLogo") as Image;
我最終使用了應用程序資源:
<Application.Resources>
<BitmapImage x:Key="testLogo" >file:///C:/Users/test_B&W.png</BitmapImage>
</Application.Resources>
然后在代碼中:
Resources["AVItestLogoic"] = ...
這樣,無論可視樹發生什么情況,應用程序資源始終指向正確的項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.