2017-04-21 70 views
0

用戶控件之間的結合我有一個項目的解決方案如下WPF的MVVM:從不同的項目

solution with different project in MVVM

起始窗被MainWindowStart.xaml位於ProjectStart.View與DataContext的ProjectStartViewModel.cs

MainWindowStart.xaml包括2個用戶控件(MyUC1.xaml,MyUC2.xaml),它們位於一個不同的項目(PROJECT1)用的DataContext Project1ViewModel.cs as showen。這些屬性正確綁定在MainWindow的InitializeComponent()上,但在屬性更改時不起作用。 它工作正常時,用戶控件包含在位於用戶控制的一些項目窗口

這是財產的一個視圖模型視圖模型

private int _IndexTabMain; 

    public int IndexTabMain 
    { 
     get { return _IndexTabMain; } 
     set 
     { 
      if (_IndexTabMain != value) 
      { 
       _IndexTabMain = value; 
       this.RaisePropertyChanged("IndexTabMain"); 
      } 

     } 
    } 

的代碼,這是代碼財產MyUC2.xaml是從選擇變化通知MyUC1.xaml

<TextBlock Text="{Binding DataContext.IndexTabMain, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"> 

在預先綁定謝謝 曼努埃爾

+0

作爲一般規則,你不應該明確地設置用戶控件的DataContext的。這樣做有效地防止了DataContext從父控件或窗口繼承,這通常會破壞您的Bindings。見例如這裏:http://stackoverflow.com/a/28982771/1136211 – Clemens

+0

定義的IndexTabMain屬性在哪裏? – mm8

+0

您的UserControl應該在您的ViewModel綁定的表面上公開DependencyProperties。就像TextBox具有Text屬性一樣,您的用戶控件應該有一個綁定到視圖模型的Whatever屬性的Whatever屬性。 – Will

回答

0

如果IndexTabMain在父窗口的視圖模型定義,您應該AncestorType屬性設置爲Window

<TextBlock Text="{Binding DataContext.IndexTabMain, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=Window}}">