Page 1 of 1

Resolving Binding for Dependency Property Returns Empty String

Posted: 03 Jun 2025, 19:52
by aivanov
Hello! I have a Dependency Property on a custom user control and I am trying to set the value using a Binding. The string is correctly saved to the DataContext but the value of the Dependency Property returned by GetValue() in `OnLoaded` is an empty string.

The issue seems to be with how the dependency property itself is setup because in the adjacent text block the string displays correctly. Additionally, hard coding the string value like: <local:InputActionGlyph Action="MyActionName"/> also works. What might be going wrong here?

Code Behind:
public partial class InputActionGlyph : UserControl
{
	public static readonly DependencyProperty ActionProperty = DependencyProperty.Register(
            "Action", typeof(string), typeof(InputActionGlyph));
        
        public void OnLoaded(object sender, EventArgs args)
        {
        	var a = (string)GetValue(ActionProperty); // The value of a is empty string
        }
}
View:
<local:InputActionGlyph Action="test"/> <!-- This works -->
<local:InputActionGlyph Action="{Binding MyActionName}"/>	<!-- This doesn't work -->
<TextBlock Text="{Binding MyActionName}"/> 	<!-- This works -->

Re: Resolving Binding for Dependency Property Returns Empty String

Posted: 04 Jun 2025, 12:15
by sfernandez
Hi,

I replicated your user control and created a small Unity example and everything works as expected.
You can find it here to check what do you have different in your project.
CustomControlTest.unitypackage
(6.12 KiB) Downloaded 985 times
Hope this helps.

Re: Resolving Binding for Dependency Property Returns Empty String

Posted: 04 Jun 2025, 22:16
by aivanov
Hello! Thank you for your reply! It made me realize that there must be some other code which is preventing the binding from happening correctly and this made me realize that InputActionGlyph also has a model.

The correct binding is actually:
 Action="{Binding DataContext.MyActionName, ElementName=MyGrid}" 
Hopefully this helps someone in the future!

For reference:
public partial class InputActionGlyph : UserControl
{
	public static readonly DependencyProperty ActionProperty = DependencyProperty.Register(
            "Action", typeof(string), typeof(InputActionGlyph));
        
        public void OnLoaded(object sender, EventArgs args)
        {
        	var a = (string)GetValue(ActionProperty); // The value of a is empty string
        }
        
        public InputActionGlyph()
	{
		InitializeComponent();
		DataContext = new InputActionGlyphModel();
		// ...
	}
	
	// ...
}

Re: Resolving Binding for Dependency Property Returns Empty String

Posted: 05 Jun 2025, 01:59
by jsantos
Thanks for your feedback!