22

我已经创建并将在这个问题中引用的文件是:

TechnicainSelectionView.xaml
TechnicianSelectionView.cs
TechnicianSelectionViewModel.cs
Technician.cs (Code First Entity)

我的 TechnicanSelectionView.xaml 中有以下 xaml

<UserControl xmlns etc... here" 
             d:DesignHeight="48" d:DesignWidth="300">
    <Grid>
        <StackPanel>
            <Label Content="Select a Technican to run the test" FontWeight="Bold"></Label>
            <ComboBox ItemsSource="{Binding Technicians, Mode=TwoWay}"></ComboBox>
        </StackPanel>
    </Grid>
</UserControl>

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<Technician> Technicians { get; set; }

    public TechnicianSelectionViewModel()
    {
        Technicians = new ObservableCollection<Technician>();
    }

    public bool IsLoaded { get; private set; }

    public void LoadTechnicians()
    {
        List<Technician> 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;
    }
}

技术人员是我的 ViewModel 上的一个属性...

因此,已经为视图设置了 DataContext,为什么它不能将 ViewModel 上的 Technicians 解析为它要绑定的 DataContext/property?

编辑:

根据下面评论中的担忧。这是设计时问题,而不是编译时问题。我应该在一开始就指出这一点。

4

2 回答 2

45

您需要在 xaml 中指定数据上下文的类型以获得设计时支持。即使您在代码隐藏中分配了数据上下文,设计人员也不会认识到这一点。

尝试将以下内容放入您的 xaml:

d:DataContext="{d:DesignInstance vm:TechnicianSelectionViewModel}"

有关更多详细信息,请参阅此链接

于 2013-02-26T23:54:35.810 回答
2

在我的 Xamarin Forms Xaml 文件中,我在标题(ContentPage 标记)中使用了以下几行,它可以按我的意愿完美运行。

基本上现在

  • 智能感知显示绑定中的字段
  • 如果我重构属性的名称,我的 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}}"
    
于 2017-02-12T09:36:06.807 回答