Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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
 
Share this answer
 
v2
Comments
Mohammed Hameed 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 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 6-Jun-13 2:16am    
Now, please see my update to the question, after [EDIT]. It that what you meant?
—SA
Mohammed Hameed 6-Jun-13 2:40am    
Yes, correct.
Sergey Alexandrovich Kryukov 6-Jun-13 7:45am    
All right. Makes sense.
—SA
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.

VB
''' <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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900