I have been trying to understand and get something working with dependency properties.
I have read loads of descriptions and explanations about DP's, and I also think I understand where they should be used.
I have read this and the links / references contain therein.
However, im still having problems. These maybe just mental blockages, maybe im clinging onto some idea or belief that i cant let go of.. anyway..
What im trying to do is create a control with a DP on it. Use that control in xaml and bind to the DP.
When i specify a value for the DP in the xaml the value is diaplayed on the user control as expected.
<DpTestProj:UserControl1 MyName="Steve"
However when i try to bind to it the value is not set, and i get
System.Windows.Data Error: 40 : BindingExpression path error: 'PersonName' property not found on 'object' ''UserControl1' (Name='')'. BindingExpression:Path=PersonName; DataItem='UserControl1' (Name=''); target element is 'UserControl1' (Name=''); target property is 'MyName' (type 'String')
Which suggests i have done something wrong with the binding or datacontext somewhere. But i cant see what.
My code is as follows.
UserControl1 has the following DP
public const string MyNamePropertyName = "MyName";
public string MyName
{
get
{
return (string)GetValue(MyNameProperty);
}
set
{
SetValue(MyNameProperty, value);
}
}
public static readonly DependencyProperty MyNameProperty = DependencyProperty.Register(
MyNamePropertyName,
typeof(string),
typeof(UserControl1),
new UIPropertyMetadata("No Name"));
Its used on the MainWindow like this
<StackPanel x:Name="LayoutRoot">
<DpTestProj:UserControl1 MyName="{Binding PersonName}" MyList="{Binding SomeListItems}" />
</StackPanel>
I'm using MVVM Light si the data context of the MainWindow is
DataContext="{Binding Main, Source={StaticResource Locator}}">
PersonName is a normal CLR (string) property that lives on the MainViewModel
If its easier I have posted the entire solution here