76265

Silverlight: How to Make a ShallowCopy of a UIElement

Question:

I need to add a UIElement to two different canvases, but one UIElement can only be a child of ONE canvas, so I have to create a ShallowCopy (DeepCopy not needed) of the UIElement.

I want to use MemberwiseClone, but it's protected, I cannot use it.

I also want to define an extension method UIElement.ShallowCopy, but it sill still call MemberwiseClone, which is protected again.

EDIT:

Tried all the following, but all of them failed in Silverlight environment:

// System.Runtime.Serialization.InvalidDataContractException was unhandled by user code // Message=Type 'System.Windows.UIElement' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required. public static T CloneEx<T>(this T obj) where T : class { T clone; DataContractSerializer dcs = new DataContractSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { dcs.WriteObject(ms, obj); ms.Position = 0; clone = (T)dcs.ReadObject(ms); } return clone; } // This one also throws Access/Invoke exceptions private readonly static object _lock = new object(); public static T MemberwiseCloneEx<T>(this T obj) where T : class { if (obj == null) return null; try { Monitor.Enter(_lock); T clone = (T)Activator.CreateInstance(obj.GetType()); PropertyInfo[] fields = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (PropertyInfo field in fields) { object val = field.GetValue(obj, null); field.SetValue(clone, val, null); } return clone; } finally { Monitor.Exit(_lock); } } // System.MethodAccessException was unhandled by user code // Message=Attempt by method 'ToonController.ControllerUtils.MemberwiseCloneEx<System.__Canon>(System.__Canon)' to access method 'System.Object.MemberwiseClone()' failed. public static T MemberwiseCloneEx<T>(this T obj) where T : class { if (obj == null) return null; MethodInfo mi = obj.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic); if (mi == null) return null; return (T)mi.Invoke(obj, null); }

Answer1:

if you have something that you want to use in multiple ui elements, 'sync them up' then you should create a ViewModel or something similar. This viewmodel would be set to the datacontext of any element you want to use it. Then your shallow reference is simple and you can just create two independent UI elements binding to the same data.

Recommend

  • Uncaught ReferenceError using external script & jQuery Mobile
  • GWT RequestFactory throws java.lang.UnsupportedOperationException: from ValueCodex.getTypeOrDie
  • Get title from link, PHP Simple HTML DOM Parser
  • Using a cursor in a stored procedure to loop rows MySQL
  • Query to select tables with similar column values
  • How to translate this slider value change from AppleScript to JavaScript
  • Unable to load external TTF fonts
  • BroadcastReceiver doesnt start from service
  • WPF DevExpress TextEdit - “ * ” for Password input
  • How to concatenate 2 function in php
  • PHPword, get total number of pages
  • How to load simple text file with float number matrix / table into Scilab
  • Xml access next node
  • How to insert a data from one table to another table selecting it for a combobox?
  • JMS Exception what type of exception is this?
  • How to install JDK and Intellij IDEA on ARM/Samsung series 3
  • Open Vimdiff with multiple windows in different read/write permissions?
  • Changing TkInter Scale won't update label “bg”
  • How to Parse data of next node in xml file
  • XSLT with test and otherwise
  • “import and using may not appear after a type declaration” — the haxe using magic
  • Jersey: How to register MultiPartConfigProvider class
  • jQuery's resizable plugin: Which handle is used? [closed]
  • Some 'utf-8' codec can't decode byte
  • Getting the indices of an unsorted double array after sorting
  • How do I optimize Python Code?
  • Paging for Gridview doesn't work correct
  • How to Unearth the Buried Regression Line in GGPLOT
  • How do I get Java EE to work?
  • Accessing an embedded device's GPIO pins via Java SE Embedded
  • C++ classes getting value using pointers and strcpy [closed]
  • how to deploy jenkins on the jetty correctly?
  • How to do network Ping .NET
  • How to fetch data using foreach in one form codeignter [closed]
  • Session Listener in Spring Mvc Google app engine
  • Is there something that behaves like .wait() and .notify() in EJB environment?
  • How to check that @Async call completed in Spring?
  • java.lang.IllegalStateException: PWC1227: Cannot forward after response has been committed…why it wa
  • Insert values in mySQL using wcf REST and Android
  • Database for Google App Engine and desktop application
  • What to put into jta-data-source of persistence.xml that works on all vendors?
  • Emacs: How to enable a mode globally?
  • Modify UIDatePicker selection indicator tint color
  • My mails are sent as spam, i use php mail()
  • Using java generics to ensure that argument received is same as class or subtype thereof
  • NumPy: Comparing Elements in Two Arrays
  • Java 8 stream unpredictable performance drop with no obvious reason
  • groovy Hashmap - get the value count from a map
  • Javascript. Extract values from associative array
  • add two linear regression lines and two y axis in ggplots [closed]
  • Split a html code in two equal content parts, in PHP or JS
  • sum/aggregate data based on dates, R
  • Using a Pipe to Write and Read Array of Int
  • How to traverse SimpleXML to edit text nodes?
  • Binary operator '*' cannot be applied to operands of type 'Float' and 'Floa
  • Programming language that makes the smallest executables? [closed]
  • Performance of behaviorally identical conditional checks [duplicate]
  • Fatal Error in JRE
  • How can i make my html control organized by bootstrap
  • Cannot import tensorflow-gpu
  • ASP.Net - DropDownList used in EditItemTemplate in DetailsView
  • How can I use JSON and Perl (HTML::Mason) to create dynamic web page with AJAX?
  • How to make a j2me project in NetBeans 7.0?
  • Understanding geolocation example
  • illegal start of type error Netbeans swing
  • C# exchanging values between forms
  • How to query many to many relationships on django?
  • Why convert string date to date javascript not working in chrome?
  • Build path specifies execution environment J2SE-1.4. error in eclipse
  • What values are used as reference to calculate the color code here?
  • How can I use libcurl function “curl_easy_setopt(CURL *handle, CURLOPT_DNS_LOCAL_IP4, char *address)
  • Plotting point estimates with error bars for different groups
  • HTML 5 semantic tags
  • Tomcat crashes JVM due to EXCEPTION_ACCESS_VIOLATION
  • Apache: Redirect domain to other domain with appended querystring
  • Xamarin Forms Reverse PushModalAsync
  • Device Capture with VLCJ
  • Commit transaction after exception - undo setRollbackOnly
  • can i use java library for java se in java me
  • Invoke constructor inside a linq query [duplicate]
  • Creating XML with JAXB KieServicesClient fails (KIE 6.5.0)
  • Linear code specification
  • Python click button with requests
  • Embed image into a textbox
  • Multiple Checkboxes array with checked and unchecked values
  • Can anyone explain the $pty argument in ssh2_exec() function call
  • Remove grey from legend in ggplot2
  • SQL Database and Java
  • Service Fabric FabricRuntime.dll not found
  • android-How to check location is in special area?
  • Update error column parameter does not exist
  • Socket server not connect with JavaScript socket client
  • JavaFX count appearance of different strings in Tableview without iterating?
  • stdin/stdout communication between Java program and C program under 64 bit windows 7
  • appStoreReceiptURL Error
  • Share a login cookie/session between domains in Rails 5
  • Prediction of 'mlm' linear model object from `lm()`
  • Wrap text inside row in tkinter treeview
  • Can you set a cookie only for domain.tld and www.domain.tld?
  • C# Constructor - why default constructor is generated by compiler only if there is no constructor, i
  • “Error: Continuous value supplied to discrete scale” in default data set example mtcars and ggplot2
  • MVC3 Controller constructor + Ninject
  • Update subset of values in a dataframe column
  • SQL: Error when converting varchar to datetime
  • In Swift Array, is there a function that returns the last index based in where clause?
  • Python converting strings in a list to numbers
  • how to run a .jar 1.7 program with an older version java 1.6?
  • Why to avoid dynamic SQL queries ? any suggestion to remove there bad part and to use these?
  • Unable to increase heap size for JMeter on Mac OSX
  • mac java 9 gradle ClassNotFoundException: javax.xml.bind.JAXBElement when building
  • preg_split is case insensitive with special characters
  • How to package an Android Library for Android Studio
  • WeakReference and memory leaks
  • Java 9 migration javax.annotation
  • Exceptions: Is this a good practice?
  • Error while uploading a new version of an Android app [duplicate]
  • XmlSerialization with a singleton
  • Installing Mathics under Mac Os X
  • Performance and static method versus public method
  • Get a list of orders in magento extension that have a certain product
  • error when inserting dataframe into MS-SQL with Python
  • Lock a window position to another window?
  • SSRS Show Textbox on last page separately
  • Java applet not working in firefox
  • Get Image uint8 data without canvas
  • how to implement Step definitios from gherkin feature files
  • Is libpq more like a JDBC driver or JavaSE's java.sql package?
  • Scala: How to require that a type have parameterless constructors
  • cannot use raw_input if monkeyrunner is included in python script
  • Class.forName() and ClassNotFoundException
  • DOMDocument::getElementById returns NULL [duplicate]
  • Three.js - how can I update an arrowHelper?
  • adding a legend to a scatterplot with fitted line and prediction interval
  • TinyXML - any way to skip problematic DOCTYPE tag?
  • Typedef with two sets of brackets?
  • Can someone explain how Postgresql roles, Postgresql users and Linux users relate to each other?
  • Inject a new instance of an object into each request handler
  • How to enable UIDragInteraction on Custom UIViews for iPhone
  • How to load JQuery faster?
  • Problem with sockets and OutOfMemory error
  • What’s the most idiomatic way to implement a “floating tag” in Git?
  • synchronization on single statement?
  • draw9patch just hangs on Mac 10.7.5
  • Delivering and using an Azure REST-API SharedKey for Blob Upload
  • Android SAXParser, parse into array and get child nodes
  • Combine multiple objects within a list
  • How to make a modal JFrame or another JComponent?
  • Implementing Images in HTML using XML
  • Difference between File>Close and :close in Vim
  • How can i create a big file in google drive with google app script?
  • How can I seek key of dictionary by index value?
  • How to add header and Footer to each activity in android
  • jQuery & CSS - Cut text by height, no truncate
  • Android VideoView Quality is so bad on TV Box using Vitamio Library
  • split dataframe into multiple dataframes based on number of rows
  • PHP + MySQL - Autocomplete from database not getting data from table
  • Is storing an OAuth token in cookies bad practise?
  • How do I get KendoUI Validator to ignore hidden form elements?
  • Can I run Robotium tests automatically in parallel on multiple emulators?
  • Restructure php contact form
  • How can I encode a filename according to RFC 2231?
  • How to re-render views using Angular JS
  • Underlying type for Tuple in Swift
  • Express.js : POST data as KEY of a req.body object instead of VALUE of req.body?
  • Differences between drawing an Ellipse in Android and Java
  • Laravel lmutator $this->attributes return 'Undefined index: id'
  • CSS Grid, position absolute an element in a css grid item: IMPOSSIBLE
  • css background images not always displayed
  • how to get data attributes of dynamically generated element
  • How to display special characters in SQL server 2008?
  • Activation Function choice for Neural network
  • unable to get jsonEncode in magento2
  • Android Studio Can't Find tools.jar
  • UWP/C# - Issue with AQS and USB Devices
  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • ListItem.Attributes.Add not working
  • How can I set a binding to a Combox in a UserControl?
  • Create DicomImage from scratch using Dcmtk
  • Ensure fsync did its job
  • How to change the font size of a single index for UISegmentedControl?
  • Get data from AJAX - How to
  • Google cloud sdk not working when python points python3
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Cannot Parse HTML Data Using Android / JSOUP
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • JTable with a ScrollPane misbehaving
  • Angular 2 constructor injection vs direct access
  • How do I configure my settings file to work with unit tests?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • unknown Exception android
  • Binding checkboxes to object values in AngularJs
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?