I am working in WPF and I am creating some userControl which some of them are inside others.
In the code behind of one of my userControls I created a dependency property as below:
(MyInnerControl.xaml.cs)
public static DependencyProperty MyDependencyProperty = DependencyProperty.Register(
"MyProperty",
typeof(Object),
typeof(MyInnerControl));
public Object MyProperty
{
get
{
return (Object)GetValue(MyDependencyProperty );
}
set
{
SetValue(MyDependencyProperty , value);
}
}
...
...
And this property works perfectly, But then I try to expose this dependency in another userControl as below:
In my code behind of my container userControl:
(MyContainerControl.xaml.cs)
public static DependencyProperty MyExternalDependencyProperty = DependencyProperty.Register(
"MyExternalProperty",
typeof(Object),
typeof(MyContainerControl));
public Object MyExternalProperty
{
get
{
return (Object)GetValue(MyExternalDependencyProperty );
}
set
{
SetValue(MyExternalDependencyProperty , value);
}
}
...
...
And in my XAML:
(MyContainerControl.xaml)
<UserControl x:Class="MyControls.MyContainerControl" Name="this"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="329" d:DesignWidth="535" xmlns:my="clr-namespace:MyInnerControls">
<Grid>
<my:MyInnerControl Margin="6,25,6,35" MyProperty="{Binding ElementName=this, Path=MyExternalProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
...
...
Finaly I add MyContainerControl to a grid and do the binding to my viewModel as below:
(AnotherContainer.xaml)
...
<MyContainerControl MyExternalProperty="{Binding MyExternalProperty}"/>
...
My problem is that my ExternalProperty does not get or set any value. What am I doing wrong?
Just to clarify, my DataContext is properly set.
Hope someone can help me, thank you in advance.
It looks to me that the problem is caused by the fact that you’re not following the Dependency Property naming conventions, which is to set your dependency property name to
<ProperyName>Property(e.g.MyExternalProperty) and using a CLR property wrapper with the same name, but omitting the “Property” suffix (in this case,MyExternal). Following this convention should solve your problems.From MSDN – Dependency Properties Overview:
EDIT: A few more things:
"MyProperty"instead of"MyDependency"and"MyExternalProperty"instead of"MyExternalDependency"thisas a name for any of your controls, as it’s a reserved keyword.