I have usercontrol where I am trying to set the DataContext
as below:
<UserControl.DataContext>
<Binding ElementName="dataGrid" Path="MyV开发者_运维技巧iewModel">
</Binding>
</UserControl.DataContext>
Here dataGrid
is a child DataGrid
control and MyViewModel
is my ViewModel
class. Currently its giving following error while runtime:
Cannot find source for binding with reference 'ElementName=dataGrid'. BindingExpression:Path=MyViewModel; DataItem=null; target element is 'UserControl1' (Name=''); target property is 'DataContext' (type 'Object')
Can anyone please help what is the problem here?
The issue is most likely due to Name Scoping constraints. ElementName Bindings only work properly within defined boundaries. This specific error is saying that it can't find the named element "dataGrid". Can you show more of the surrounding XAML?
Is MyViewModel set on the DataContext of dataGrid?
If so change MyViewModel in Path to DataContext and you are good to go... If not, set your MyViewModel class to DataContext and remove the ElementName from the Binding, and it should work as well ;)
This binding tries to access dataGrid.MyViewModel
, but MyViewModel
is not a property of the DataGrid
... You should do something like that instead :
<Binding ElementName="dataGrid" Path="DataContext.MyViewModel">
精彩评论