Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I need to further qualify the DataContext for a binding?

Tags:

The files I have created and will be referring to in this question are:

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

I have the following xaml in my TechnicanSelectionView.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> 

The Technicians property to which the ItemSource is set to bind to states that it Cannot resolve Technicians due to an unknown DataContext.

So if we look to my TechnicianSelectionView.cs code-behind...

public partial class TechnicianSelectionView : UserControl {     public TechnicianSelectionViewModel ViewModel { get; private set; }      public TechnicianSelectionView()     {         InitializeComponent();          Technician.GenerateSeedData();          ViewModel = new TechnicianSelectionViewModel();         DataContext = ViewModel;     } } 

... we see that I am setting the view's DataContext to my 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;     } } 

Techicians is a property on my ViewModel...

So having already set the DataContext for the view, why can't it resolve Technicians on the ViewModel as the DataContext/property it is going to bind to?

EDIT:

As per a concern in a comment below. This is a design time problem and not compile time. I should have indicated this at the start.

like image 820
Isaiah Nelson Avatar asked Feb 26 '13 23:02

Isaiah Nelson


1 Answers

You need to specify the type of data context in the xaml to get design-time support. Even though you assigned the data context in code-behind, the designer is not going to recognize that.

Try putting the following in your xaml:

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

See this link for more details.

like image 168
Brandon Baker Avatar answered Oct 07 '22 16:10

Brandon Baker