无事件的 C# WPF 序列化 XAML

标签 c# wpf xaml serialization

我在 Canvas 中动态创建了控件,当我序列化 Canvas 事件时,未序列化。

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>

这可能吗? 谢谢

最佳答案

根据以下 MSDN article ,这是不可能的。

Event Handling is Not Preserved

When event handlers that are added through XAML are serialized, they are not preserved. XAML without code-behind (and also without the related x:Code mechanism) has no way of serializing runtime procedural logic. Because serialization is self-contained and limited to the logical tree, there is no facility for storing the event handlers. As a result, event handler attributes, both the attribute itself and the string value that names the handler, are removed from the output XAML.

关于无事件的 C# WPF 序列化 XAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45425092/

相关文章:

c# - 如何使用 C# Windows 窗体读取 Excel 中的多个单元格

c# - 跨不同屏幕尺寸缩放 WPF 应用程序中的元素

c# - WPF中的动画GIF问题

silverlight - 在 Silverlight 应用程序中显示 pdf。 PDF 转 XAML

c# - 在 CellTemplate 中为 ListView 创建触发器? (一般与模板混淆)

c# - 三元运算符用法

c# - Web API发布返回415-不支持的媒体类型

c# - 将数据集保存到数据库

wpf - 如何在WPF扩展器控件上设置TabIndex?

wpf - 在扩展 WPF 工具包 PropertyGrid 中选择编辑器