开发者

Error while setting a Datacontext for a UserControl in WPF

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">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜