Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a ItemsControl whose Itemssource is bound to a collection of customWidgets as follows:
<ItemsControl ItemsSource ="{Binding MyCustomWidgets}">
 <ItemsControl.ItemTemplate>
  <DataTemplate>
   <CustomWidget Name="{Binding Name}" 
     SomeOtherDP="{Binding SomePropertyOfaCustomWidget}" 
     EditButtonCommand="{Binding   Path=MyButtonCommand,DataContext=MyViewModel}
   </CustomWidget>
  </DataTemplate>
 </ItemsControl.ItemTemplate>
</ItemsControl>

The ViewModel:
public class MyViewModel
	Inherits ViewModelBase
	public Property MyCustomWidgets as ObservableCollection(Of CustomWidget)
	   ... omitted for brevity    
        End Property
	
	Public Property MyButtonCommand as ICommand
	   ... omitted for brevity
	End Property
End Class

The Widget usercontrol has a button on it that is internally bound to a Custom Dependency property of type ICommand named EditButtonCommand

I want all properties of the Widget except the EditButton to bind to an instance of CustomWidget.
But I want the EditButton (i.e. the custom dependency property of the Widget) to bind to the MyButtonCommand Property of the same MyViewModel instance that the ItemsControl's datacontext is set to, not the CustomWidget.
It seems that I should be able to point the Button Binding to the datacontext of the ItemsControl (whose datacontext is set to the ViewModel) using some sort of relative ancestor verbage, but I can't figure out how to do this.
Does anyone know how to do this?
Posted

Hello, You can bind the Command property for Button in ItemsControl as follow -
HTML
<Button x:name="button1" Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext.MyButtonCommand}" Commandparameter="{Binding ElementName=button1}" />


So that you can bind EditButtonCommand same as above Button Command property.
 
Share this answer
 
v3
Comments
Member 8617640 29-Jan-14 11:54am    
I am trying to understand how this solves the problem. I don't have a separate button element, the EditButton is embedded in the UC. The UC has a dependency property called EditButtonCommand that internally (to the UC) routes the binding to the embedded edit button element.
I figured it out after much trial and error.
EditButtonCommand ="{Binding DataContext.EnableCommand, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ItemsControl}}}"

This is the correct xaml code to solve the problem. I still don't quite understand all of this. I get the FindAncestor of type ItemsControl, but what is the seemingly redundant "RelativeSource={RelativeSource ..." about?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900