【问题标题】:WPF Binding to a property obtained from a DataTemplateWPF 绑定到从 DataTemplate 获得的属性
【发布时间】:2016-05-06 16:27:24
【问题描述】:

我想将一个对象的属性绑定到其子对象之一的类似属性,而此子内容(包括相关属性的值)是从DataTemplate 获得的。如果重要的话,这一切都发生在UserControl 中。

<UserControl.Resources>
  <DataTemplate x:Key="RText">
    <TextBlock Text="TextR" ToolTip="TextR"/>
  </DataTemplate>
</UserControl.Resources>

<StackPanel x:Name="LayoutRoot" ToolTip="{Binding Path=ToolTip, ElementName=TemplText, FallbackValue='error'}">
  <TextBlock Text="Some common static text " />
  <ContentControl x:Name="TemplText" ContentTemplate="{StaticResource RText}" />
</StackPanel>

另外,在代码隐藏中,在这个控件的构造函数中,有一个赋值

LayoutRoot.DataContext = this

这显然是绑定到UserControl 自己的属性所必需的(这在sn-p 中没有显示)。我想这个问题无论如何都没有关系,但我确实需要这条线。

想法是这样的:整个StackPanel (LayoutRoot) 应该与ContentControl (TemplText) 具有相同的ToolTip。但是,此工具提示应取自指定模板,即在本例中为“TextR”。

这种方法的根本原因是ContentControl 最终将通过一个相当复杂的DataTemplateSelector(分配给ContentTemplateSelector 而不是ContentTemplate)来选择,我想避免为一般工具提示。我宁愿在所选模板中包含工具提示,然后将其向上传播以覆盖整个控件。包括 ToolTip 在内的所有元素也将更加精细,而不仅仅是 TextBlock,而且将整个 (StackPanel) 做成一个可选择的模板是不切实际的。

上面的代码在没有为整个控件显示工具提示的意义上不起作用;它只显示TemplText。但是,FallbackValue 也没有显示,这表明路径没有问题:它找到了元素但大概是直接从它(即null)而不是从模板中获取了ToolTip

这个问题有解决办法吗?或者也许只是一种更好的 WPF 方法来实现相同的结果?我是 WPF 新手。

我了解DataTemplate 本身没有工具提示;这是它的元素之一。但是我怎么能引用它呢?或者我应该以某种方式使用属于模板的样式?

【问题讨论】:

    标签: .net wpf xaml data-binding datatemplate


    【解决方案1】:

    1.在Window.Activated事件的代码中设置你的Binding

    private void Window_Activated(object sender, EventArgs e)
    {
        Binding b = new Binding("ToolTip");
        b.Source = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(TemplText, 0), 0);
        LayoutRoot.SetBinding(StackPanel.ToolTipProperty, b);
    }
    

    2.从ViewModel中的属性设置ToolTip

    <DataTemplate x:Key="RText">
        <TextBlock x:Name="Tb" Text="TextR" ToolTip="{Binding ToolTipProp}"/>
    </DataTemplate>
    
    <StackPanel x:Name="LayoutRoot" ToolTip="{Binding DataContext.ToolTipProp, ElementName=TemplText}">
    

    【讨论】:

    • 这里的ToolTipProp 是什么?
    • 这将是您的视图模型中的一个属性。您将定义此属性。这将是一个普通的 CLR 属性,因为不需要 2 路绑定。
    • 但这假设我以编程方式分配工具提示?..但我不想这样做。整个想法是代码应该只选择DataTemplate,并且模板会静态定义适当的工具提示。给定模板只有一个合适的工具提示。
    猜你喜欢
    • 2016-01-11
    • 2015-09-09
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2018-09-30
    • 2018-04-26
    • 1970-01-01
    • 2011-06-27
    相关资源
    最近更新 更多