Search code examples
c#wpfobjectcloning

How to create two object with the same properties - Cloning not working


I have to create two datagrid with the same properties:

var dtg = new DataGrid
{
    Margin = new Thickness(10),
    EnableColumnVirtualization = false,
    EnableRowVirtualization = false,
    Background = Brushes.Transparent,
    Foreground = new SolidColorBrush(m_ExeCfg.GetForeground()),
};

and then dtg2 with the same properties... but Datagrid dtg = dtg2 = {...} is not allowed

therefore I have used this cloning:

string dtgXaml = System.Windows.Markup.XamlWriter.Save(dtg);
StringReader stringReader = new StringReader(gridXaml);
System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
DataGrid dtg2 = (DataGrid)System.Windows.Markup.XamlReader.Load(xmlReader);

so how can I create two objects with exactly the same properties?


Solution

  • Looks like you are sererializing to dtgXaml, but that is never used. Instead you use some gridXaml variable.

     string dtgXaml = System.Windows.Markup.XamlWriter.Save(dtg);
     StringReader stringReader = new StringReader(gridXaml);