2012-07-11 58 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