2017-07-31 21 views
2

我在畫布中動態創建控件,並且當我序列化Canvas事件時沒有序列化。沒有事件的C#WPF序列化XAML

Label label = new Label(); 
... 
label.MouseLeftButtonDown += Control_MouseLeftButtonDown; 
label.MouseLeftButtonUp += Control_MouseLeftButtonUp; 
label.MouseMove += Control_MouseMove; 
label.MouseLeave += Control_MouseLeave; 
... 

public static string SerializeXAML(UIElement element) 
{ 
    string strXAML = System.Windows.Markup.XamlWriter.Save(element); 
    return strXAML; 
} 

public static UIElement DeserializeXAML(string XAML) 
{ 
    return System.Windows.Markup.XamlReader.Parse(XAML) as UIElement; 
} 

序列化字符串:

<Canvas Background="#FFFFFFFF" Name="DesignCanvas" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><Label FontSize="12" Focusable="True" Canvas.Left="363.146190476191" Canvas.Top="179.774339118825" Panel.ZIndex="2">Label</Label></Canvas> 

我想<Label ... MouseLeftButtonDown="Control_MouseLeftButtonDown">text</Label>

這是可能的嗎? 謝謝

回答

2

根據以下MSDN article,這是不可能的。

事件處理,不保留

當被通過XAML添加的事件處理程序序列化,它們不會保留。沒有代碼隱藏的XAML(也沒有相關的x:Code機制)沒有辦法序列化運行時過程邏輯。由於序列化是獨立的並且僅限於邏輯樹,因此沒有用於存儲事件處理程序的功能。因此,從輸出XAML中刪除事件處理程序屬性,包括屬性本身和命名處理程序的字符串值。

+0

我正要寫相同的答案。幾乎一字不差。它也擊敗了我! :) –

+1

哈哈哈,jinx沒有蘇打水給你;)。 –