YH Kim
YH Kim

Reputation: 31

Binding viewmodel to view has usercontrol with own viewmodel

I have a UserControl 'UserControlA' with ViewModel 'ViewModelA'. 'UserControlA' has 'UserControlB', and 'UserControlB' has 'ViewModelB'.

When I bind a DependencyProperty in 'UserControlA' with 'ViewModelA' property, there is none of setter fired.

Belows are code,

ViewA.xaml

<UserControl
         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:vm="clr-namespace:MyTest.ViewModel
         xmlns:custom="clr-namespace:MyTest.Views
         x:Name="userControl" x:Class="MyTest.Views.UserControlA"             
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="500">

<UserControl.DataContext>
    <vm:UserViewModel x:Name="uvModel"/>
</UserControl.DataContext>
<Grid>
<custom:UserControlB></custom:UserControlB>

ViewA.cs

public partial class UserView : UserControl, IUserView
{        
    static DependencyProperty UserTypeProperty = DependencyProperty.Register("UserType", typeof(UserType), typeof(UserView), new PropertyMetadata(UserType.None));
    public UserType UserType { get { return (UserType)GetValue(UserTypeProperty); } set { SetValue(UserTypeProperty, value); } }
    public ViewA()
    {
        InitializeComponent();

        Binding typeBinding = new Binding();
        typeBinding.Source = this.DataContext;
        typeBinding.Path = new PropertyPath("User.UserType");
        typeBinding.Mode = BindingMode.OneWayToSource;
        this.SetBinding(UserTypeProperty, typeBinding);           
    }

ViewModelA.cs

public class ViewModelA : ViewModelBase
{

    User user = new User();
    public User User
    {
        get { return this.user; }
        set
        {
            this.user = value;                
            RaisePropertyChanged(() => User);                
        }
    }

Please help me out from this problem.

Upvotes: 0

Views: 84

Answers (1)

Clemens
Clemens

Reputation: 128146

The line

typeBinding.Source = this.DataContext;

is redundant, because the DataContext is implicitly used as source object of the Binding.

However, during the execution of the UserControl's constructor the DataContext property is not yet set (i.e. it is null), so you are effectively setting the Binding's Source property to null. Just remove that line, or write

SetBinding(UserTypeProperty, new Binding
{
    Path = new PropertyPath("User.UserType"),
    Mode = BindingMode.OneWayToSource
}); 

Upvotes: 1

Related Questions