Reputation: 204746
My View
<UserControl x:Class="Views.PartView"
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"
xmlns:viewModels="clr-namespace:EComponents.ViewModels"
mc:Ignorable="d"
x:Name="PartUc"
d:DataContext="{d:DesignInstance viewModels:PartViewModel}">
<Grid>
<TextBox x:Name="NameTb" Text="{Binding Name}" />
</Grid>
</UserControl>
My ViewModel
public class PartViewModel : ViewModel<Part>
{
public PartViewModel(Part model) : base(model)
{
PartListViewModel.OnSelectedPartChanged += PartListViewModel_OnSelectedPartChanged;
}
void PartListViewModel_OnSelectedPartChanged(Part p)
{
Model = Part.GetPart(p);
}
public string Name
{
get
{
return Model.Name;
}
set
{
if (Name != value)
{
Model.Name = value;
this.OnPropertyChanged("Name");
}
}
}
}
My Model
public class Part
{
public string Name { get; set; }
}
I don't know why but the TextBox in my UserControl does not get filled with the Name property of my part even though this line is called
Model = Part.GetPart(p);
I set the DataContent of my View like this
public partial class PartView : UserControl
{
public PartView()
{
InitializeComponent();
DataContext = new PartViewModel(new Part());
}
}
Upvotes: 0
Views: 95
Reputation: 33364
Is seems as if you don't notify UI when Model
is changed in PartListViewModel_OnSelectedPartChanged
. You need to call this.OnPropertyChanged(...)
for every Model
related property after it's changed or call it with null argument this.OnPropertyChanged(null)
to refresh all properties
void PartListViewModel_OnSelectedPartChanged(Part p)
{
Model = Part.GetPart(p);
this.OnPropertyChanged(null);
}
Upvotes: 2
Reputation: 19635
You have a slight issue in your code:
if (Name != value)
{
Model.Name = value;
this.OnPropertyChanged("Name");
}
Should be:
if (Model.Name != value)
{
Model.Name = value;
this.OnPropertyChanged("Name");
}
Self-referencing the Name property of your view model will give you issues.
Last but not least you need code in your code-behind to bind the DataContext at runtime.
Edit
I just took a look at your code again as well as the comments on the question. When you set the value of Model in the event handler, you need to set DataContext there as well. Changing the model reference doesn't update the DataContext.
Upvotes: 0