DependencyProperty represents a property that can be set through methods such as, styling
, data binding
, animation
, and inheritance
.
TextBox's Text property is a DependencyProperty, and I will show my sample of binding data to it with MVVM. You need to read the Basic data binding concepts to know how the data is bound before starting.
Model Part:
public class PersonModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string name;
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChange("Name");
}
}
private int age;
public int Age
{
get { return age; }
set
{
age = value;
OnPropertyChange("Age");
}
}
}
View Part:
<Window.DataContext>
<local:PersonViewModel></local:PersonViewModel>
</Window.DataContext>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" Content="Name:"/>
<TextBox Grid.Column="1" Grid.Row="0" Text="{Binding User.Name,Mode=TwoWay}" Width="200" HorizontalAlignment="Left" Height="30" />
<Label Grid.Column="0" Grid.Row="1" Content="Num:" />
<TextBox Name="txtNum" Grid.Column="1" Grid.Row="1" Text="{Binding User.Age,Mode=TwoWay}" HorizontalAlignment="Left" Height="30" Width="200"/>
</Grid>
ViewModel Part:
class PersonViewModel
{
private PersonModel user;
public PersonModel User
{
get { return user; }
set
{
user = value;
}
}
public PersonViewModel()
{
User = new PersonModel { Name = "John", Age = 11 };
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.