wpf - 在 DataTemplates 中使用 TemplateBinding

标签 wpf binding datatemplate

我正在创建一个自定义控件,但在将 DataTemplate 内的 UI 元素绑定(bind)到自定义控件的依赖属性时遇到问题。

我的控件中有一个内容控件,应该根据某个属性更改其内容和内容模板,所以我这样绑定(bind)它 -

<ContentControl Content="{TemplateBinding ControlMode}" ContentTemplateSelector="{StaticResource TemplateSelector}"/>

内容模板选择器是这样定义的 -

<ns:TemplateSelector x:Key="TemplateSelector">
      <ns:TemplateSelector.Template1>
         <DataTemplate>
            <TreeView ItemsSource="{TemplateBinding TreeSource}"/>
         </DataTemplate>
      </ns:TemplateSelector.Template1>
      <ns:TemplateSelector.Template2>
          <DataTemplate>
              <ListView ItemsSource="{TemplateBinding ListSource}"/>
          </DataTemplate>
      </ns:TemplateSelector.Template2>
</ns:TemplateSelector>

问题在于,由于此错误,TreeView 和 ListView 无法使用 TemplateBinding 绑定(bind)到其项目源 -

“在 ContentPresenter 类型上找不到 TreeSourceProperty”

我一直在寻找答案,我发现这个答案很简单,表明这是不可能的。

How to use template binding inside data template in custom control (Silverlight)

因此,如果这确实不可能,我还能如何将模板内的元素绑定(bind)到 CustomControl 的 DependencyProperties?

谢谢!

最佳答案

在 WPF 中,您可以使用 RelativeSource 的绑定(bind)针对“模板化”控件。

例如

{Binding TreeSource,
         RelativeSource={RelativeSource AncestorType=MyCustomControl}}

编辑:如果你在树上有一个中断,你可以通过传递该控件来解决这个问题,例如

<ControlThatOwnsPopup
    Tag="{Binding RelativeSource={RelativeSource AncestorType=MyCustomControl}}">
     <Popup>...
<TreeView ItemsSource="{Binding PlacementTarget.Tag.TreeSource,
                                RelativeSource={RelativeSource AncestorType=Popup}}"/>

关于wpf - 在 DataTemplates 中使用 TemplateBinding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9409057/

相关文章:

wpf - 将 RichTextBox 绑定(bind)到字符串

wpf - 如何在WPF中打印长帐单

c# - MVVM跨安卓: value with binding not updated

c# - ApplicationBar 绑定(bind) Windows Phone

asp.net - 具有三层架构的 Entity Framework ,跨域的不同实体

c# - MainWindow.xaml 打开时运行项目花费的时间太长 - WPF

c# - Java 和 C# 处理方法绑定(bind)方式的显着差异背后的解释是什么?

c# - 从 DataTemplate 绑定(bind) ZIndex

wpf - 您可以在 DataTemplate 中使用 CollectionViewSource 吗?

wpf - 如何在 WPF 中声明将 Itemsource 作为枚举值的组合框 itemTemplate?