附加的依赖项属性值是否可以传播给模板化的子项?
示例:尝试将TagCloudService。*属性传播到ItemTemplate
<ItemsControl x:Name="myItemsControl"
pages:TagCloudService.MaximumFontSize="20"
pages:TagCloudService.MaximumFontWeight="800"
pages:TagCloudService.MinimumFontSize="10"
pages:TagCloudService.MinimumFontWeight="400"
pages:TagCloudService.NumberOfSizes="5"
pages:TagCloudService.TagFrequency="{Binding Hotttnesss}"
pages:TagCloudService.TagWeight="{Binding Weight}"
Template="{StaticResource TagCloudItemsControlTemplate}">
<ItemsControl.ItemTemplate>
<StaticResource ResourceKey="TermTagCloudTemplate" />
</ItemsControl.ItemTemplate>
</ItemsControl>
这是项目模板,其中已定义了一些默认值但应该被覆盖:
<DataTemplate x:Key="TermTagCloudTemplate" DataType="api:Term">
<TextBlock Foreground="DodgerBlue"
Padding="10"
Style="{StaticResource TagCloudTextBlockStyle}"
Text="{Binding Name}"
pages:TagCloudService.MaximumFontSize="30"
pages:TagCloudService.MaximumFontWeight="800"
pages:TagCloudService.MinimumFontSize="20"
pages:TagCloudService.MinimumFontWeight="400"
pages:TagCloudService.NumberOfSizes="5"
pages:TagCloudService.TagFrequency="{Binding Frequency}"
pages:TagCloudService.TagWeight="{Binding Weight}">
</TextBlock>
</DataTemplate>
我尝试设置FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior而不是.Inherits,尝试在模板中注释默认值,但不传播属性。
这可能或者我应该为该控件创建另一个ItemTemplate吗?
答案 0 :(得分:2)
实际上很容易。
使用Inherits
声明附加属性 - 选项:
public static string GetFoo(DependencyObject obj)
{
return (string)obj.GetValue(FooProperty);
}
public static void SetFoo(DependencyObject obj, string value)
{
obj.SetValue(FooProperty, value);
}
public static readonly DependencyProperty FooProperty =
DependencyProperty.RegisterAttached(
"Foo", typeof(string), typeof(MainWindow),
new FrameworkPropertyMetadata(
"default",
// this bit is important:
FrameworkPropertyMetadataOptions.Inherits));
测试XAML:
<Grid src:MainWindow.Foo="non-default">
<TextBlock Text="{Binding (src:MainWindow.Foo),
RelativeSource={RelativeSource Self}}"/>
</Grid>
显示&#34;非默认&#34;。
这也适用于模板边界,完整示例如下。
<Window x:Class="DPInheritance.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:DPInheritance"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="Test">
<TextBlock Text="{Binding (src:MainWindow.Foo),
RelativeSource={RelativeSource Self}}"/>
</DataTemplate>
</Window.Resources>
<Grid src:MainWindow.Foo="non-default">
<ItemsControl ItemTemplate="{StaticResource Test}">
<sys:Int32>0</sys:Int32>
<sys:Int32>1</sys:Int32>
<sys:Int32>2</sys:Int32>
</ItemsControl>
</Grid>
</Window>