2012-07-11 24 views
0

我是新來的WPF和C#。在另一個類中訪問控件或對象(如文本框,按鈕等)的最佳方式是什麼?下面解釋我的情況。如果這有所作爲,我也使用MEF。任何幫助,將不勝感激。 謝謝。使用控件我有一個類與另一個類

EsriMapView.xaml是包含所有對象的位置。 這個類是EsriMapView.xaml.cs。

EsriMapViewModel.cs是我嘗試訪問EsriMapView.xaml的另一個類。我在所有對象上收到的錯誤是「名稱空白在當前上下文中不存在」。

下面是從XAML類的代碼:

[Export] 
    [PartCreationPolicy(CreationPolicy.NonShared)] 
    public partial class EsriMapView : DialogWindowBase 
    { 
     //private int? initialZoom = null; 
     //private double? latitude = null; 
     //private double? longitude = null; 

     //private string json = string.Empty; 
     //private ObservableCollection<LocationPoint> marks = null; 
     //private bool isZoomToBounds = false; 

     //private string startPoint = string.Empty; 
     //private string endPoint = string.Empty; 

     //private string searchPoint = string.Empty; 

     public EsriMapView() 
     { 
      InitializeComponent();    
     } 

     [Import] 
     public EsriMapViewModel ViewModel 
     { 
      get 
      { 
       return this.DataContext as EsriMapViewModel; 
      } 
      set 
      { 
       this.DataContext = value; 
      } 
     } 

    } 
} 

我也使用MVVM。如果您需要更多信息,請告訴我。再次感謝。

回答

0

您不應該試圖從您的視圖模型訪問您的視圖。這違反了MVVM的原則之一,這使得測試您的虛擬機變得困難。相反,你的VM應該暴露視圖​​綁定的屬性。虛擬機然後可以訪問它完成工作所需的數據。

作爲一個簡單的例子,假設您的視圖模型需要知道當前縮放級別才能執行一些計算。在您的視圖模型,你會:

public double Zoom 
{ 
    get { return this.zoom; } 
    set 
    { 
     if (this.zoom != value) 
     { 
      this.zoom = value; 
      this.RaisePropertyChanged(() => this.Zoom); 
     } 
    } 
} 

private void DoSomeCalculation() 
{ 
    // can use this.zoom here 
} 

然後,在你的看法:

<Slider Value="{Binding Zoom}"/> 
+0

那麼你覺得我該怎麼辦有關啓用和禁用某些對象 – JLott 2012-07-11 18:15:16

+0

@JLott:再次,你的虛擬機公開屬性(在啓用控件的情況下可能是布爾屬性),視圖綁定到這些屬性(在這種情況下可能是'IsEnabled')。在這種情況下,你將需要一個綁定轉換器,因爲源類型('bool')與目標類型('Visibility')不匹配。請參見[BooleanToVisibilityConverter](http://msdn.microsoft.com/zh-cn/library/system.windows.controls.booleantovisibilityconverter.aspx)。 – 2012-07-11 18:22:05

+0

謝謝。這非常有幫助:) – JLott 2012-07-11 19:28:33