I think I may be using the DependencyObject incorrectly.
I have a generic class that implements the DependencyObject called Person with the properties FirstName and LastName.
public class Person : DependencyObject
{
public static readonly DependencyProperty FirstNameProperty =
DependencyProperty.Register("FirstName", typeof(string), typeof(Person));
public string FirstName
{
get { return (string)GetValue(FirstNameProperty); }
set { SetValue(FirstNameProperty, value); }
}
public static readonly DependencyProperty LastNameProperty =
DependencyProperty.Register("LastName", typeof(string), typeof(Person));
public string LastName
{
get { return (string)GetValue(LastNameProperty); }
set { SetValue(LastNameProperty, value); }
}
}
Then I have a xaml control with its datacontext set to my ViewModel class. Inside the ViewModel class I have a property called UserName that gets/sets a Person. The text box is bound to the UserName.FirstName property. It can populate the textbox correctly but can’t seem to call the set when I enter characters and tab out. I think the issue is the two level property binding. For design reasons I need to access it through two levels of properties. Any suggestions?
Here is my xaml:
<TextBox Width="100" Margin="10,0,0,0" Text="{Binding Path=UserName.FirstName, Mode=TwoWay}" />
Here is my property in the view model class:
public Person UserName
{
get
{
return person;
}
set
{
person = value;
}
}
I’ve also tried it this way too:
public Person UserName
{
get
{
return person;
}
set
{
person.FirstName = value.FirstName;
}
}
Your property will not be called from the binding, the property is only there because of the pattern so it is easily visible from code.
The binding sets the dependency property directly.
Why do you want dependency properties in this situation? Dependency properties are relevant on controls – for your scenario use regular properties and INotifyPropertyChanged – the code will be simpler that way 🙂
If you do want notification when a dependencyproperty is changed you have to add a static eventhandler to the DependencyProperty.Register(…) call.