【问题标题】:WPF xaml, have child element inherit parent propertyWPF xaml,让子元素继承父属性
【发布时间】:2015-05-21 16:09:27
【问题描述】:

我试图让一个子元素从它的父标签项继承颜色。因此,不必单独设置每种背景颜色,我只需设置 tabitem 颜色,剩下的就交给我了。我尝试了很多不同的东西,但没有任何效果。在 VS 中,使用下面发布的代码,当我选择了 ScrollViewer 并在属性窗口中单击背景颜色绑定中的转到源时,它会突出显示 tabitem 背景属性,但颜色不会改变。抱歉,我前几天才开始学习 xaml。

 <TabItem Name="PD" Header="Product Details" Background="#FFB5CFE2"  FontFamily="Vrinda" VerticalAlignment="Stretch" >
            <ScrollViewer VerticalScrollBarVisibility="Auto" MaxHeight="750" VerticalAlignment="Stretch" Margin="-4,-5,-4,-4" Background="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=TabItem}}">....

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    运行应用程序时,VS 中的输出窗口会显示绑定错误。您可能会说:“System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TabItem', AncestorLevel='1''。BindingExpression:Path=背景;DataItem=null;目标元素是 'ScrollViewer' (Name='');目标属性是 'Background'(类型 'Brush')"

    基本上发生的事情是 TabItem 和选项卡的内容在可视化树中是分开的,您将无法通过查看树从 TabContent 中找到 TabItem 本身。请参阅此 SO 答案以获得直观的解释:RelativeSource in DataTemplate works with TabControl but not with TabItem

    我建议您从这里有几个选择,

    • 按元素名称引用 TabItem:

      &lt;ScrollViewer Background="{Binding Background, ElementName=PD}"&gt;

    • 创建一个静态资源并在项目之间使用它:

      <SolidColorBrush Color="#FFB5CFE2" x:Key="PDBackgroundBrush"/> <ScrollViewer Background="{StaticResource PDBackgroundBrush}"/>

    【讨论】:

    • 谢谢,我能够使用名称引用让它工作,但有点希望反对它,因为那样我每次我都必须去更改滚动查看器中的引用名称创建一个新选项卡。但是,回头看,无论如何我都必须插入绑定事件,而且我想我可以多花 2 秒钟来更改名称。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 2021-05-21
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多