【问题标题】:Stackpanel in styleStackpanel 风格
【发布时间】:2011-09-14 10:41:58
【问题描述】:

使用 windows.resource 中的下一个代码块。

<Style TargetType="Button" x:Key="l1" >
    <Setter Property="Button.Effect" >
    <!--<Setter Property="BitmapEffect">-->
        <Setter.Value>
            <DropShadowEffect />
        </Setter.Value>
    </Setter>
    <Setter Property="Content" >
        <Setter.Value >
            <StackPanel  Orientation="Horizontal">
                <Image Source="Resources\find.bmp" Stretch="Uniform" ></Image>
                <TextBlock>Find</TextBlock>
            </StackPanel>
        </Setter.Value>
    </Setter>
</Style>

它仅适用于一个按钮,但一旦我将它应用于在运行时生成的第二个按钮错误。

<Button Height="23" HorizontalAlignment="Left" Margin="322,25,0,0" Name="Button18" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />
<Button Height="23" HorizontalAlignment="Left" Margin="586,37,0,0" Name="Button19" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" />

有解决这个问题的办法吗?

【问题讨论】:

  • 你实际上得到了什么错误?

标签: wpf xaml styles stackpanel


【解决方案1】:

您不能以这种方式直接设置ContentControlContent。原因是Content 设置器中的StackPanel(仅举一个例子)对于应用该样式的所有按钮来说是同一个实例;但是,这是不允许的(并且可能导致您得到 Element is already the child of another element 异常)。

相反,您应该设置ContentTemplate 属性:

<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="Resources\find.bmp" Stretch="Uniform" ></Image>
                <TextBlock>Find</TextBlock>
            </StackPanel>
        </DataTemplate>
    </Setter.Value>
</Setter>

这将起作用,因为现在将为模板的每个实例创建一个新的可视化树分支(即,StackPanels 等将与您拥有的按钮一样多)。

【讨论】:

    【解决方案2】:

    您不能通过这样的样式设置控件的内容(至少不能两次)。

    您应该使用模板来发送内容,如下所示:

        <DataTemplate x:Key="buttonTemplate">
            <StackPanel  Orientation="Horizontal">
                <Image Source="Resources\find.bmp" Stretch="Uniform" ></Image>
                <TextBlock>Find</TextBlock>
            </StackPanel>
        </DataTemplate>
        <Style TargetType="Button" x:Key="l1" >
            <Setter Property="Button.Effect" >
                <Setter.Value>
                    <DropShadowEffect />
                </Setter.Value>
            </Setter>
            <Setter Property="ContentTemplate" Value="{StaticResource buttonTemplate}" />
        </Style>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多