I have the following simple code:
<Window x:Class="WpfApplication3.MainWindow"
x:Name="WindowInst" …>
<local:UserControl1/>
</Window>
<UserControl x:Class="WpfApplication3.UserControl1" …>
<Button Content="Click me"
Command="{Binding DataContext.ButtonClickedCommand,
ElementName=WindowInst}" Height="134" Width="314" />
</UserControl>
And in the ViewModel for the Window I have ButtonClickedCommand:
#region Avatar click command
RelayCommand _buttonClickedCommand;
public ICommand ButtonClickedCommand
{
get
{
if (_buttonClickedCommand == null)
{
_buttonClickedCommand = new RelayCommand(() => this.ButtonClicked());
}
return _buttonClickedCommand;
}
}
public void ButtonClicked()
{
}
#endregion
Unfortunately, it causes exception at runtime:
System.Windows.Data Error: 4 : Cannot find source for binding with reference ‘ElementName=WindowInst’. BindingExpression:Path=DataContext.ButtonClickedCommand; DataItem=null; target element is ‘Button’ (Name=”); target property is ‘Command’ (type ‘ICommand’)
Could you explain me what’s wrong with it?
Try modifying your binding as follows…
This should work as
WindowInstdoes not live withinSelfsince your container is theUserControl; which is being placed within theWindow. In addition you need to make sure that you are setting yourDataContextwithin theWindowor its value will benulland no binding will ever occur no matter if your syntax is accurate or not.