1

I have a DataTemplate that have put in a ResourceDictionary, and there is a button in the DataTemplate and I put this DataTemplate in a window. Now I want to bind the Button Command to a property of windowViewModel,how can I do that? this is the code:

 <DataTemplate DataType="{x:Type types:User}" x:Key="UserTemp"> <Grid > <Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ????}, AncestorLevel=1}, Path=SelectLocationCommand}" /> </Grid> </DataTemplate> 

and in Window.xaml

<ContentControl x:Name="UserTemp" /> 

and in WindowViewModel:

 public ICommand SelectLocationCommand { get {return new RelayCommand(selectLocationCommand); } } void selectLocationCommand() { _welcomeTitle = "AA"; } 

1 Answer 1

2

The short answer is that you don't need to do it in code.

You defined your DataTemplate as a template for a "User" object. This means that this is how a User object should be shown in the UI. So, in order to use your DataTemplate you should have a "User" instance in your WindowViewModel. This means that the SelectLocationCommand should be in the User object and not in the WindowViewModel.

Having said all that, your code should look somthing like this:

In Window.xaml

<ContentControl Content="{Binding User}" ContentTemplate="{StaticResource UserTemp}" /> 

In WindowViewModel

public User User {get;set} 

In User

public ICommand SelectLocationCommand { get {return new RelayCommand(selectLocationCommand); } } void selectLocationCommand() { _welcomeTitle = "AA"; } 

Also, make sure that the Window.xaml's DataContext is WindowViewModel. There's a number of better ways to do this but the easiest would be:

In Window.xaml.cs

public MainWindow() { InitializeComponent(); this.DataContext = new WindowViewModel(); } 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks alex,but i dont want to put SelectLocationCommand in the User Class!!actually user is the entity Class!
There are solutions to have the command in the parent ViewModel, if you could just give a few more details about your design I might help you better. When you say the User is actually the Entity class, do you mean that's the Model?
thanks alex,it has a realy simple solution, you just need to set a name for the window and in the dataTemplate bindig,Specifies the elementname into that name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.