Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: .NET2.0 C#2.0 .NET3.0 C#3.0 VS2008 , +
How to enumerate through properties of textbox in Wpf (using C#)?
 
Actually I wanted to create a clone of textbox by copying all properties same to this cloned textbox except the Id/Name of the textbox so that they both would be different textboxes.
 
I think I can achieve the same by using XamlWriter but I wanted to check if there is any other suitable alternate.
 
I hope that my question is clear and to the point. But if it has created any confusions please let me know.
 
Thanks.
Posted 5-Jun-13 20:22pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

This can be done using Reflection. But won't it be an overkill? Reflection can do a lot more; it can clone objects in type-agnostic manner, through type metadata discovery, when you have no preexisting knowledge of the type, but you are talking about one fixed type. Besides, reflection is relatively slow.
 
So, are you sure that you don't want just to code cloning manually? No? Then drill down in this direction:
 
First, get a runtime type: http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx[^].
 
You got the instance of System.Type. Now, get the properties: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx[^].
 
With each property, you can access property values through its getter and setter. You will need a type instance, a reference for which you can get or set a property value:
http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx[^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.canread.aspx[^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.canwrite.aspx[^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getmethod.aspx[^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.setmethod.aspx[^].
 
The last two links shown above explain how to obtain getter and setter. It has the type MethodInfo:
http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx[^].
 
Finally, you use a getter or a setter to get or set the property variable, through using the invocation method:
http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx[^],
http://msdn.microsoft.com/en-us/library/4k9x6bc0.aspx[^].
 
Basically, that's it. You have source object, its reference, create a new object, obtain its reference. Read all properties in one, set in another one, using the two references, which are passed as the parameter named obj in one of two invocation methods referenced above.
 
[EDIT]
 
I just described the most universal approach, fully type-agnostic. You can also consider type-specific approach. Please see my comment below; let's assume shallow cloning, by the reasons I explained. (However, we can consider deep cloning, which I actually tried out; it is not available in .NET as something actually existing.)
 
You need to derive all types you want to clone, and, if they not implement System.IClonable, implement it. Please see:
http://msdn.microsoft.com/en-us/library/system.icloneable.aspx[^].
 
Perhaps this is what you already know, then I'm just confirming its applicability.
 
—SA
  Permalink  
v2
Comments
Mohammed Hameed at 6-Jun-13 2:06am
   
Hi Sergey. Thanks for your quick answer. +5 for it (as always you are one of fav Expert at Code project) :)
Anyhow the Reflection technique also I'm already aware of but obviously don't want to use it.
So I think its better to go ahead with cloning only as it seems much better option. If somebody asks me like why I have accepted your answer because I love the way you have explained about Reflection and has given informative links, which I think that surely helps other guys who come across this question.
Sergey Alexandrovich Kryukov at 6-Jun-13 2:11am
   
Is it deep or shallow cloning? However, there isn't much deep with TextBox, only such things are font, but you would better want them shallow-cloned...
—SA
Sergey Alexandrovich Kryukov at 6-Jun-13 2:16am
   
Now, please see my update to the question, after [EDIT]. It that what you meant?
—SA
Mohammed Hameed at 6-Jun-13 2:40am
   
Yes, correct.
Sergey Alexandrovich Kryukov at 6-Jun-13 7:45am
   
All right. Makes sense.
—SA
Edo Tzumer at 6-Jun-13 2:50am
   
5+ (because there's no optional 6)
Sergey Alexandrovich Kryukov at 6-Jun-13 7:45am
   
Thank you, Edo.
—SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

This cloning looks like a big problem in WPF? If the object is not serializable you can't use the deepclone solution with deserialisation.
 
The solution at the bottom clones a UI object by its properties.
Sadly I could not get it to work to copy the event handlers also.
 
''' <summary>
''' Clone object, by copying all properties NOT THE EVENT HANDLERS
''' </summary>
''' <param name="o"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function CloneObjectByProperties(o As Object) As Object
    Try
        'get all properties if the type
        Dim t As Type = o.[GetType]()
        Dim properties As PropertyInfo() = t.GetProperties()
        'instantiate a new object for the found type
        Dim p As [Object] = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, Nothing, o, Nothing)
        'copy all properties
        For Each pi As PropertyInfo In properties
            If pi.CanWrite Then
                pi.SetValue(p, pi.GetValue(o, Nothing), Nothing)
            End If
        Next
 
        ''Copy handlers
        'Dim _copyHelper As New clsCopyEventHandlers()
        'Try
        '    _copyHelper.GetHandlersFrom(o).CopyTo(p)
        'Catch ex As Exception
        '    'just continue, could not copy events
        'End Try

        Return p
    Catch ex As Exception
        Throw New Exception("CloneObjectByProperties failed: " & ex.Message)
    End Try
 
End Function
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 365
1 Sergey Alexandrovich Kryukov 334
2 CPallini 275
3 DamithSL 230
4 Maciej Los 215
0 OriginalGriff 5,455
1 DamithSL 4,457
2 Maciej Los 3,885
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,115


Advertise | Privacy | Mobile
Web02 | 2.8.141216.1 | Last Updated 17 Jun 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100