Isa*_*son 21 c# data-binding wpf mvvm
我在这个问题中创建并将引用的文件是:
TechnicainSelectionView.xaml
TechnicianSelectionView.cs
TechnicianSelectionViewModel.cs
Technician.cs (Code First Entity)
Run Code Online (Sandbox Code Playgroud)
我的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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
...我们看到我正在将视图的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;
}
}
Run Code Online (Sandbox Code Playgroud)
Techicians是我的ViewModel上的一个属性...
因此,为视图设置了DataContext,为什么它不能将ViewModel上的技术人员解析为它要绑定到的DataContext /属性?
根据以下评论的关注点.这是设计时问题而不是编译时间.我应该在开始时说明这一点.
Bra*_*ker 41
您需要在xaml中指定数据上下文的类型以获得设计时支持.即使您在代码隐藏中分配了数据上下文,设计人员也不会认识到这一点.
尝试在xaml中添加以下内容:
d:DataContext="{d:DesignInstance vm:TechnicianSelectionViewModel}"
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅此链接.