CodingYourLife CodingYourLife - 1 year ago 80
C# Question

WPF DependencyProperty override Uid for all Controls

Reason why I want to do this is UI automation. Our UI automation software finds elements via Name/Uid attribute. The name attribute can't bind to anything and the Uid seems to only have a OneTime binding (even if set to OneWay). Binding the Tag property works but has a visual consequence. So the idea was to create my own property for all UI elements that override the Uid property.

Here is what I have so far and how I thought it could work

namespace MyApplication.Shared.Controls
public class RxUidAttributeExtension : Control
public static readonly DependencyProperty RxUidProperty = DependencyProperty.RegisterAttached("RxUid", typeof(string), typeof(RxUidAttributeExtension), new FrameworkPropertyMetadata("", RxUidChanged)
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged

private static void RxUidChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
var metadata = RxUidProperty.GetMetadata(typeof(RxUidAttributeExtension));
UidProperty.OverrideMetadata(typeof(UIElement), new UIPropertyMetadata("RxOverridden")); //override Uid property -> exception

public static string GetRxUid(DependencyObject d)
return (string)d.GetValue(RxUidProperty);

public static void SetRxUid(DependencyObject d, string value)
d.SetValue(RxUidProperty, value);

And in xaml:

<DockPanel Name="myNameNeverChanges"
controls:RxUidAttributeExtension.RxUid="{Binding MyProperty, Mode=OneWay}" />

What I want is that changes on RxUid should affect the Uid property.

Why I think this should work: Link - "you can override metadata for any dependency property".
The exception says something about already registered :/

  • List item

Answer Source

Ok it works like @Clemens suggested but it seems also OneWay of Uid works so my whole question is obsolete. It's just the Ranorex Spy Tool that didn't show the changed Uid correctly. The tests work perfectly it's just the Spy Tool that has this little flaw.

Here is a version that is a bit cleaner instead of casting:

d.SetValue(UIElement.UidProperty, e.NewValue); //override Uid property