2016-11-02 7 views
0

私はViewModel 'ViewModelA'を持つUserControl 'UserControlA'を持っています。 'UserControlA'には 'UserControlB'があり、 'UserControlB'には 'ViewModelB'があります。ビューにバインドするviewmodelには、自分のビューモデルでusercontrolがあります。

'ViewModelA'プロパティで 'UserControlA'のDependencyPropertyをバインドすると、 はセッターが実行されません。

belowsのコード、

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

この問題から私を助けてください。 DataContextのが暗黙的バインディングのソースオブジェクトとして使用されるため

+0

ここでは間違っているようですが、質問を編集して原因があるかどうかはわかりません。あなたのDP定義にはgetter/setterがなく、あなた自身が '自分のviewmodelでusercontrolを持っている 'と主張していますが、あなたのコードには(ひどいコードの臭いが)表示されませんし、ViewModelAにはViewModelB UserControlBがViewModelAにネストされている場合は、それが必要です。 – Will

+0

ああ、すみません。私は質問を更新し、いくつかのコードを追加しました。 –

答えて

1

typeBinding.Source = this.DataContext; 

は、冗長です。あなたが効果的にnullへのバインディングSourceプロパティを設定しているので、

しかし、DataContextプロパティがまだ設定されていないUserControlのコンストラクタの実行中に、(すなわち、それはnullです)。その行を削除するか書き込んでください

SetBinding(UserTypeProperty, new Binding 
{ 
    Path = new PropertyPath("User.UserType"), 
    Mode = BindingMode.OneWayToSource 
}); 
関連する問題