silverlight CustomControl 中的 TemplateBinding DataContext
我有一个相当有趣的 ComboBox 控件案例 - CustomComboBox;
在此 ComboBox 的样式中,Popup 包含一个请求 DataContext 的自定义控件;
<ctrl:CustomGrid DataContext="{TemplateBinding DataContext}" GridName="{Binding Preferences.CurrentGridName}"/>
想法:
- 要在一个页面上多次使用此控件,
- 以便在母版页容器中使用它,
- 母版页控件需要有关于其所在页面的不同 DataContext
逻辑:
- 在覆盖的 OnApplyTemplate 中,我获取网格并连接几个事件处理
程序问题:
- 母版页控件仅触发 OnApplyTemplate 一次
- CustomComboBox 的第一次出现符合预期。 但是,每次出现都具有相同的 DataContext,即使更改 CustomComboBox 的数据上下文也是如此 这些更改不会改变我的 CustomGrid DataContext
我确信绑定或表示逻辑上的某些内容是不好的...... 请提出一些想法,我希望在这里得到提示,
谢谢
I have a rather interesting case with ComboBox control - CustomComboBox;
In the style of this ComboBox, Popup contains one custom control that requests a DataContext;
<ctrl:CustomGrid DataContext="{TemplateBinding DataContext}" GridName="{Binding Preferences.CurrentGridName}"/>
The idea:
- to use this control several times on one page
- to use it in a masterpage container
- the masterpage control needs to have different DataContexts regarding the Page it is on
The logic:
- In the overriden OnApplyTemplate I am getting the grid and connecting few eventhandlers
The problem:
- The masterpage control is triggering OnApplyTemplate only once
- The first appearance of the CustomComboBox is as expected.
However, every next apearance is with same DataContext, even when changing the datacontext of the CustomComboBox
These changes don't reach to change my CustomGrid DataContext
I am sure that something on the bindings or the presentation logic is bad...
Please throw some thoughts on, I would appreciate a hint here
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当将
ControlTemplate
应用于覆盖该方法的控件(无论是其父项还是子项)时,都会调用OnApplyTemplate
。如果输入一次OnApplyTemplate
,则覆盖控件也必须创建一次。我的意思是您只有一个单个母版页实例。这应该不足为奇。谈到
Popup
和DataContext
,从Popup
到外部的绑定通常会出现问题。因此,我宁愿编写一些代码隐藏来为Popup
提供正确的上下文,而不是依赖于Binding
。在 SL5 之前肯定存在 DataContextChanged 事件缺失的问题。要解决此问题,您应该在CustomComboBox
上定义自定义DependencyProperty
,将其绑定到CustomComboBox
的上下文,并将其值分配给PropertyChangedCallback
中的Popup
。OnApplyTemplate
is called when aControlTemplate
is applied to the control that overrides the method (neither its parent, nor children). IfOnApplyTemplate
is entered once, the overriding control must also be created once. I mean you simply have a single masterpage instance. This shouldn't be unexpected.Speaking about
Popup
s andDataContext
, there often are issues with bindings from aPopup
to outside it. So, I would rather write some code-behind to deliver correct context toPopup
s, instead of relying onBinding
s. There sure is a problem of DataContextChanged event absence prior to SL5. To workaround this one, you should define your customDependencyProperty
on yourCustomComboBox
, bind it to theCustomComboBox
's context and assign its value to thePopup
in thePropertyChangedCallback
.