这有什么错"的DataContext =这个"在WPF用户控件? [英] What's wrong with "DataContext = this" in WPF user controls?

查看:230
本文介绍了这有什么错"的DataContext =这个"在WPF用户控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读的地方,在用户控件的构造函数设置的DataContext =此是不好的做法(找不到在哪里虽然)。这是为什么不好的做法?什么是另类?

I read somewhere that setting DataContext = this in the constructor of a user control is bad practice (can't find where though). Why is this bad practice? What is the alternative?

推荐答案

在一般情况下,当有人使用你的控制,他们会想设置它的数据上下文他们自己的视图模型类和属性绑定在你的控制自己的视图模型。

In general, when someone uses your control they are going to want to set it's data context to their own view model class and bind the properties on your control to their view model.

如果你开始在内部控制中的数据上下文乱搞,并依靠它是设置为本,要么你会阻止他们的结合从工作,还是如预期,因为你依靠它没有被改变了你的控制将无法正常工作。

If you start messing around with the data context internally within the control, and rely on it being set to 'this', either you will prevent their binding from working, or your control won't work as expected because you rely on it not being changed.

假设你有一个有它的子控件的一群用户控件。你可以做的,而不是被设置在DataContext的子控件是你的用户控件类(或任何你想要的)。这将允许您绑定到用户控件的属性的子控件,同时还允许您控制来设置它自己的视图模型和绑定的属性以及数据上下文中的任何用户。

Say you have a user control that has a bunch on sub controls on it. What you could do instead is set the DataContext on the sub controls to be your user control class (or whatever you wanted). This would allow you to bind those sub controls to your user control's properties, while still allowing any users of your control to set it's data context to their view model and bind to the properties as well.

这篇关于这有什么错"的DataContext =这个"在WPF用户控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆