2016-11-02 23 views
0

我有一個用戶控件「UserControlA」與視圖模型「ViewModelA」。 'UserControlA'有'UserControlB','UserControlB'有'ViewModelB'。綁定視圖模型到視圖有用戶控件與自己的視圖模型

當我將'UserControlA'中的DependencyProperty與'ViewModelA'屬性 綁定在一起時,沒有任何setter被觸發。

初級講座是代碼,

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);     
     } 
    } 

請幫我解決這個問題。

+0

這裏似乎有一堆錯誤,但不知道是否由編輯問題引起的。你的DP定義缺少getters/setters,你聲稱'擁有自己的viewmodel的usercontrol',但是我沒有在你的代碼中看到(可怕的代碼味道),並且我無法判斷你的ViewModelA是否有公共屬性ViewModelB,它應該如果你的UserControlB嵌套在你的ViewModelA中。 – Will

+0

哦,對不起。我更新了問題並添加了一些代碼。 –

回答

1

typeBinding.Source = this.DataContext; 

是多餘的,因爲在DataContext被隱式地用作綁定的源對象。

然而,用戶控件的構造函數中DataContext屬性尚未設置的執行過程中(即,它是null),所以你綁定的Source財產有效地設置爲null。只要刪除該行,或寫

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