[英]Error while setting a Datacontext for a UserControl in WPF
I have usercontrol where I am trying to set the DataContext
as below: 我在尝试设置
DataContext
地方有用户控件,如下所示:
<UserControl.DataContext>
<Binding ElementName="dataGrid" Path="MyViewModel">
</Binding>
</UserControl.DataContext>
Here dataGrid
is a child DataGrid
control and MyViewModel
is my ViewModel
class. 这里
dataGrid
是一个DataGrid
子控件,而MyViewModel
是我的ViewModel
类。 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.
ElementName绑定只能在定义的边界内正常工作。 This specific error is saying that it can't find the named element "dataGrid".
此特定错误表示无法找到命名元素“ dataGrid”。 Can you show more of the surrounding XAML?
您可以显示更多周围的XAML吗?
Is MyViewModel set on the DataContext of dataGrid? 是否在dataGrid的DataContext上设置MyViewModel?
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 ;) 如果是这样,则将Path中的MyViewModel更改为DataContext,您就可以开始使用...如果不行,请将MyViewModel类设置为DataContext并从Binding中删除ElementName,它也应该工作;)
此绑定尝试访问dataGrid.MyViewModel
,但是MyViewModel
不是DataGrid
的属性...您应该执行类似的操作:
<Binding ElementName="dataGrid" Path="DataContext.MyViewModel">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.