【发布时间】:2011-12-07 05:59:53
【问题描述】:
问题
我创建了一个自定义控件 (OmniBox),它的基本样式设置为:
<Style x:Key="GridStyle" TargetType="Grid" BasedOn="{StaticResource BaseElement}">
<Setter Property="Margin" Value="0,2" />
</Style>
但是当我使用我的控件时,我希望能够执行以下操作:
<UserControl.Resources>
<Style TargetType="{x:Type ui:OmniBox}">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Margin" Value="0,10"/> <!--Not Working?-->
</Style>
</UserControl.Resources>
<Grid>
<StackPanel>
<ui:OmniBox x:Name="One"... />
<ui:OmniBox x:Name="Two"... />
...
并让我的控件的所有实例都采用该默认边距。不幸的是,我的控件没有响应资源中设置的样式。他们只是保持默认的“0,2”边距。
奇怪的是,如果我像这样显式设置控件的边距:
<ui:OmniBox x:Name="One" Margin="0,10" Style="OBDefaultStyle" ... />
<ui:OmniBox x:Name="Two" Margin="0,10" ... />
...
他们确实使用“0,10”而不是“0,2”的边距。为什么模板类型不起作用?
如果相关,我的 OmniBox 控件模板都如下所示:
<Style TargetType="{x:Type local:OmniBox}" x:Key="OBDefaultStyle">
<Setter Property="Template" Value="{StaticResource OBDefaultTemplate}" />
</Style>
<ControlTemplate TargetType="{x:Type local:OmniBox}" x:Key="OBDefaultTemplate">
<Grid x:Name="PART_Grid" Style="{StaticResource GridStyle}">
... (Content)
</Grid>
</ControlTemplate>
第一次尝试
在我的网格样式中,我尝试将 Margin 设置为
<Setter Property="Margin"
Value="{Binding Path=Margin, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:OmniBox}}}" />
但它没有帮助吸收模板边距。
第二次尝试
我尝试创建一个自定义边距依赖属性并将网格绑定到该属性:
<Style x:Key="GridStyle" TargetType="Grid" BasedOn="{StaticResource BaseElement}">
<Setter Property="Margin" Value="{Binding Path=MyMargin, RelativeSource={RelativeSource TemplatedParent}}" />
</Style>
我的自定义属性定义为:
public static readonly DependencyProperty MarginProperty = DependencyProperty.Register("Margin", typeof(Thickness), typeof(OmniBox), new FrameworkPropertyMetadata(new Thickness(0,2,0,2), new PropertyChangedCallback(OnMarginChanged)));
无论如何,它没有工作。上面依赖属性中设置的默认边距仍然覆盖了我试图在样式模板中设置的边距。
【问题讨论】: