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...
<Window x:Class="WpfApplication3.MainWindow"
x:Name="WindowInst" …>
<local:UserControl1/>
</Window>
<UserControl x:Class="WpfApplication3.UserControl1" …>
<Button Content="Click me"
Command="{Binding Path=ButtonClickedCommand, Mode=FindAncestor, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Height="134" Width="314" />
</UserControl>
This should work as WindowInst
does not live within Self
since your container is the UserControl
; which is being placed within the Window
. In addition you need to make sure that you are setting your DataContext
within the Window
or its value will be null
and no binding will ever occur no matter if your syntax is accurate or not.
Your bindings are a little off.
Please see this tutorial on WPF command binding.
As a general rule, specify as little as possible in your bindings. I don't think you need element name in this circumstance and datacontext is the assumed root of your bindings.
精彩评论