A
A
Alexander2010-09-16 23:31:51
.NET
Alexander, 2010-09-16 23:31:51

Serialization in WPF (Events)?

I am serializing my usercontrol to a WPF richtextbox.
With standard elements, everything is fine, but with its own control, trouble.
Events are not serialized, which is what MSDN says:

Event handling is not persisted
Event handlers that are added using XAML are not serialized when they are serialized. XAML without code-behind (also without an associated x:Code mechanism) has no way to serialize runtime procedural logic. Because serialization is self contained and limited to a logical tree, there is no facility to store event handlers. As a result, the event handler attributes, both the attribute itself and the string value of the handler name, are removed from the XAML output.

So I tried it with the highlighted code. It turned out like this:
(this is my control)
<DockPanel LastChildFill="False">
<Button x:Name="play" Click="play_Click" VerticalAlignment="Top" Content="Play"/>
<Button x:Name="stop " Click="stop_Click" VerticalAlignment="Top" Content="Stop"/>
<x:Code>
<![CDATA[
public void play_Click(object sender, RoutedEventArgs e)
{
me.Stop();
me.Play();
}
public void stop_Click(object sender, RoutedEventArgs e)
{
me.Stop();
</DockPanel>
And in the code like this:
public MusicControl()
{
InitializeComponent();
play.Click += new RoutedEventHandler(play_Click);// deserialization does not swear
here stop.Click += new RoutedEventHandler(stop_Click);
me.LoadedBehavior = MediaState.Manual;
me.UnloadedBehavior = MediaState.Manual;
}
public MusicControl(string path_file)
{
this.path_file = path_file;
me.LoadedBehavior = MediaState.Manual;
me.UnloadedBehavior = MediaState.Manual;
try
{
me.Source = new Uri(path_file);
}
catch { }
InitializeComponent();
play.Click += new RoutedEventHandler(play_Click);
stop.Click += new RoutedEventHandler(stop_Click);
}
MediaElement me = new MediaElement();
string path_file = "";
public string Path_file
{
get { return path_file; }
set
{
path_file = value;
me.Source = new Uri(Path_file);
}
}
But all the same after deserialization handlers do not work.
Serialization\deserialization itself:
string aaa = XamlWriter.Save(fd);
rtf.RichTextControl.Document.Blocks.Clear();
byte[] byteArray = Encoding.ASCII.GetBytes(aaa);
MemoryStream stream = new MemoryStream(byteArray);
object ddd = XamlReader.Parse(aaa);
FlowDocument deserializedXaml = ddd as FlowDocument;
What's wrong? Is it possible to make events after deserialization work?
ps A friend asked me to ask - he does not have an account.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question