【发布时间】:2022-01-18 05:12:36
【问题描述】:
我需要帮助来了解为什么这不起作用。根据 MSDN,在将模板中控件的属性绑定到实现模板的控件的属性时应该使用 TemplateBinding。
除了模板绑定不是双向的。对于双向,您需要使用绑定,然后将相对源指定为 TemplatedParent。
所以我有以下 XAML: 模板
<ItemContainerTemplate x:Key="colHeaderTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" VerticalAlignment="Center"/>
<ToggleButton Style="{StaticResource ToggleButtonStyle}" IsChecked="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Path=(props:VisibilityHelper.IsGroupCollapsed)}"/>
</StackPanel>
</ItemContainerTemplate>
这里用的
<dxg:GridColumn x:Name="Total" Header="Total" FieldName="field1" Width="Auto" HorizontalHeaderContentAlignment="Center" props:VisibilityHelper.IsGroupCollapsed="False" HeaderTemplate="{StaticResource colHeaderTemplate}">
<dxg:GridColumn.EditSettings>
<dx:TextEditSettings HorizontalContentAlignment="Center"/>
</dxg:GridColumn.EditSettings>
</dxg:GridColumn>
模板中的切换按钮必须在网格列上设置依赖属性。当模板绑定到父级时,这可以正常工作。控件是嵌套的,
我就是想不通我做错了什么。
MSDN 参考 - http://msdn.microsoft.com/en-us/library/ms742882.aspx
许多关于此的 SO 帖子之一 - In WPF, why doesn't TemplateBinding work where Binding does?
谢谢
【问题讨论】:
-
我对 WPF 有点生疏了,但如果我没记错的话,ItemContainer(顾名思义)是单元格的容器,而不是单元格小部件。也就是说,如果你想为任何类型的单元格内容可视化器/编辑器安排一个特定的容器。
-
TemplateBinding和{RelativeSource TemplatedParent}只能在ControlTemplate内部工作,而您的模板不是这个模板 - 它是DataTemplate。只要您尝试绑定到列上定义的属性,您似乎需要在绑定中设置RelativeSource到{RelativeSource FindAncestor, AncestorType={x:Type dxg:GridColumn}}。 -
ItemContainerTemplate和DataTemplate一样吗,因为我用的是ItemContainerTemplate?无论哪种方式,我都实现了您对@Quercus 的建议,但正如预期的那样,我得到了以下
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='DevExpress.Xpf.Grid.GridColumn', AncestorLevel='1''. BindingExpression:Path=(0); DataItem=null; target element is 'ToggleButton' (Name=''); target property is 'IsChecked' (type 'Nullable1')`,这是我所期望的,因为 FindAncestor 只有在我理解正确的情况下才适用于嵌套控件 -
@dracosveen
ItemContainerTemplate是DataTemplate的后代。但是,FindAncestor应该可以工作-您将模板作为HeaderTemplate传递给列,这意味着当创建列时,它将使用此模板在标题中创建实际控件,而在运行时ToggleButton将嵌套控制列的标题以及列本身。
标签: c# wpf templatebinding