0
 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.

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Hi HB Can you clarify a little bit? Sorry I am very new to MVVM and still struggling. Do I have to remove binding in ButtonVM constructor? How can I overwrite the DataContext. Is it going to be in datatemplate? I think I am trying to create views from VMs.VMs will be created from xml setting. Thanks a lot
@user1202484: Gaah, no, i cannot clarify. no time. If this too much for you have a look around, there are a lot of questions about MVVM tutorials and the like.
Thanks. I already looked at a lot. I think I am pretty close.Anyways thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.