我需要什么才能进一步限定DataContext的绑定?
我在这个问题中创建并将引用的文件是:
TechnicainSelectionView.xaml TechnicianSelectionView.cs TechnicianSelectionViewModel.cs Technician.cs (Code First Entity)
我的TechnicanSelectionView.xaml中有以下xaml
ItemSource设置为绑定到的Technicians属性指出Cannot resolve Technicians due to an unknown DataContext.
因此,如果我们查看我的TechnicianSelectionView.cs代码隐藏…
public partial class TechnicianSelectionView : UserControl { public TechnicianSelectionViewModel ViewModel { get; private set; } public TechnicianSelectionView() { InitializeComponent(); Technician.GenerateSeedData(); ViewModel = new TechnicianSelectionViewModel(); DataContext = ViewModel; } }
…我们看到我将视图的DataContext设置为我的TechnicianSelectionViewModel …
public class TechnicianSelectionViewModel : ViewModelBase { public ObservableCollection Technicians { get; set; } public TechnicianSelectionViewModel() { Technicians = new ObservableCollection(); } public bool IsLoaded { get; private set; } public void LoadTechnicians() { List technicians; using (var db = new TestContext()) { var query = from tech in db.Technicians select tech; foreach (var technician in query) { Technicians.Add(technician); } } IsLoaded = true; } }
Techicians是我的ViewModel上的一个属性……
因此,为视图设置了DataContext,为什么它不能解析ViewModel上的技术人员作为它要绑定的DataContext /属性?
编辑:
根据以下评论的关注点。 这是设计时问题,而不是编译时间。 我应该在开始时说明这一点。
您需要在xaml中指定数据上下文的类型以获得设计时支持。 即使您在代码隐藏中分配了数据上下文,设计人员也不会认识到这一点。
尝试在xaml中添加以下内容:
d:DataContext="{d:DesignInstance vm:TechnicianSelectionViewModel}"
有关详细信息,请参阅此链接 。
在我的Xamarin Forms Xaml文件中,我在标题(ContentPage标记)中使用了以下行,它完全按照我的意愿工作。
基本上现在
- intellisense显示绑定中的字段
-
如果我重构属性的名称,我的Resharper能够重命名Xaml文件中的绑定
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:vm="clr-namespace:YourApplicationName.ViewModels;assembly=YourApplicationName" mc:Ignorable="d" d:DataContext="{d:DesignInstance {x:Type vm:CurrentPageViewModel}}"