【问题标题】:Setting Button's Content to <Image> via Styles通过样式将按钮的内容设置为 <Image>
【发布时间】:2011-06-15 11:11:52
【问题描述】:

无法让它工作:

<UserControl>
    <UserControl.Resources>
        <ResourceDictionary>
            <Style x:Key="TestStyle" TargetType="{x:Type Button}">
                <Setter Property="Button.Content">
                    <Setter.Value>
                        <Image Source="D:\Temp\dictionary16.png"/>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </UserControl.Resources>
    <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
        <Button Style="{StaticResource TestStyle}"/>
        <Button Style="{StaticResource TestStyle}"/>
    </StackPanel>
</UserControl>

此代码抛出以下异常(指向第二个按钮):

指定元素已经是另一个元素的逻辑子元素。先断开连接。

【问题讨论】:

  • 你也可以使用附加属性来制作图片按钮
  • 是的,但好像我没看错,我必须使用一些 C#-Code,如果可能的话,我想要一些 pure-wpf/xaml-soloution。

标签: wpf image xaml button styles


【解决方案1】:

该样式创建Image 的一个实例,您不能在这样的两个地方使用它。您可以使用x:Shared= false 将图像创建为单独的资源并在样式中引用它,然后将在使用该样式的每个位置创建一个新的。


例如

<UserControl>
    <UserControl.Resources>
        <Image x:Key="img" x:Shared="false" Source="D:\Temp\dictionary16.png" />
        <Style x:Key="TestStyle" TargetType="{x:Type Button}">
            <Setter Property="Content" Value="{StaticResource img}" />
        </Style>
    </UserControl.Resources>
    <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
        <Button Style="{StaticResource TestStyle}" />
        <Button Style="{StaticResource TestStyle}" />
    </StackPanel>
</UserControl>

【讨论】:

  • 您能否在答案中提供更多代码? 就是这样我理解它,但它以相同的异常结束
  • 添加了一个对我有用的示例。 (我当然使用了不同的 Image.Source)
  • Crazy Sh***...我测试了你的独奏,它可以被解释的所有方式,我确信在其中一个我有你现在发布的完全相同的代码,但它没有工作.但是然后只是复制了您发布的代码,然后 BAAAAM 它就起作用了。谢谢大佬...
  • -1:这不是在 WPF 中处理此问题的正确方法。在我的项目中尝试过,但它不起作用,可能是因为代码在外部 DLL 中。您应该改为通过 ContentTemplate 设置内容,这将确保为每个按钮创建一个新图像。
  • @reSPAWNed:没有“正确”的方式。如果你没有让这个工作,那是你自己的错。此外,在控件不允许大量模板化的许多情况下,这是使其工作的唯一方法
【解决方案2】:

昨天我已经找到一个有类似问题的用户:WPF - Change a button's content in a style?

这篇文章让我得到了这个解决方案(由于 stackoverflow 的 8 小时限制而无法发布 -.-)

<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <Image Source="{mcWPF:LangRes imgSettings16, Bitmap}" Height="14"/>
        </DataTemplate>
    </Setter.Value>
</Setter>

不知道天气,这比 H.B. 的解决方案更干净/肮脏/更好

【讨论】:

  • 这样更简洁,我建议尽可能使用模板属性。
  • +1:标记的答案在我的场景中不起作用,但这确实......更清洁和更好的解决方案。
猜你喜欢
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多