user1202484
user1202484

Reputation: 1

Binding View Model to View in data template

   public class ToolBarView : ToolBar
{
         public ToolBarView()
         {
            this.DataContext = new ToolBarViewModel();
         }
}


public ToolBarViewModel: ViewModelBase
    {
        public ObservableCollection<ViewModelBase> Items {get;set;} 
        public ToolBarViewModel()
        {
          // populate button view models 
         Items.Add(new ButtonViewModel() {Content="Button1"});
         Items.Add(new ButtonViewModel() {Content="Button2"});
         }
    }



 public class ButtonView : Button
    {
      public ButtonView()  
      {
          this.DataContext = new ButtonViewModel();
      }
    }



 public class ButtonViewModel : ViewModelBase
    {
      public object Content {get;set;}      
    }

In MainWindow.xaml

<Window.Resources>
    <DataTemplate x:Key="buttonTemplate" DataType="{x:Type vm:ButtonViewModel}">
       <v:ButtonView Content={Binding Content}/> 
     </DataTemplate>

<v:ToolBarView ItemsSource="{Binding Items}" 
               ItemTemplate={StaticResource buttonTemplate}/>

Note: I did INotifyChanged in ViewModelBase class

In MainWindow.xaml. i think My template is wrong.ButtonView in DataTemplate is creating a new view instance. It is not binding the viewModel that was poplulated in the ToolBar Items collection. I tried to do with Relative Binding. Still not successful. Please help me out.

Upvotes: 0

Views: 1540

Answers (1)

brunnerh
brunnerh

Reputation: 185290

Just drop the line where you create a new VM and overwrite the DataContext:

this.DataContext = new ButtonViewModel();

Then the DataContext will be inherited (it will be the item in the collection, the ButtonVM).

(As a side-note, you seem to try view-first and view-model-first at the same time, you should stick with one. Also the view should probably already bind to all the relevant properties on the view-model so that you just need need to create the view and that's it)

Upvotes: 1

Related Questions