积极答复者
Style资源继承、引用的问题

问题
-
各位好,我在Sytle继承上遇到了如下的问题,不知如何解决:
1.实现TargetType={x:Type Button} x:Key="FunctionButton"的样式,并把ContentPresenter设置为{TemplateBinding Content}
2.实现TargetType={x:Type Button} x:Key="SaveButton"的样式,Baseon="{StaticResource FunctionButton}",并在SaveButton中设置Content的样式为<StackPanel>
界面添加两个按钮都是Style={StaticResource SaveButton},运行时报错:“'Set property 'System.Windows.FrameworkElement.Style' threw an exception.'”
“Specified element is already the logical child of another element. Disconnect it first”
我希望使用同一基础样式,并添加多个Baseon FunctionButton的样式,并重写Content,实现统一按钮样式。
我估计是静态样式资源抢占引起问题。
代码如下(StyleResourceErrorProject):
http://cid-7c49a2abb00e1af5.skydrive.live.com/redir.aspx?resid=7C49A2ABB00E1AF5!2706
答案
-
你好,
你的问题在于 Button 的样式中已经设置了一个Content值。这个值会在第一个Button被使用,但是WPF中Style默认是 x:Shared=“true”的,所以同样的logic tree逻辑树也会被第二个按钮使用,这个时候就会报出这个错误。即使你第二个按钮重写了Content值。
解决方法是:
<Style TargetType="{x:Type Button}" x:Key="ConfirmButton" BasedOn="{StaticResource FunctionButton}" x:Shared="False"> <Setter Property="Content"> <Setter.Value> <StackPanel Orientation="Horizontal"> <TextBlock Text="确定" Margin="10"/> </StackPanel> </Setter.Value> </Setter> </Style>
加入 x:Shared="False" 到这个样式!
Sincerely,
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 懵盛盛 2011年1月18日 2:23
全部回复
-
你好,
你的问题在于 Button 的样式中已经设置了一个Content值。这个值会在第一个Button被使用,但是WPF中Style默认是 x:Shared=“true”的,所以同样的logic tree逻辑树也会被第二个按钮使用,这个时候就会报出这个错误。即使你第二个按钮重写了Content值。
解决方法是:
<Style TargetType="{x:Type Button}" x:Key="ConfirmButton" BasedOn="{StaticResource FunctionButton}" x:Shared="False"> <Setter Property="Content"> <Setter.Value> <StackPanel Orientation="Horizontal"> <TextBlock Text="确定" Margin="10"/> </StackPanel> </Setter.Value> </Setter> </Style>
加入 x:Shared="False" 到这个样式!
Sincerely,
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 懵盛盛 2011年1月18日 2:23