c# - 按钮自定义内容在运行时不呈现

标签 c# wpf winforms wpf-style

我有一个托管在 Windows 窗体窗体中的 UserControl。在这个 UserControl 中,我有一个 ToolBar,其中有各种按钮:

<ToolBar>
   <Button Content="{StaticResource AllGreenIcon}"/>
   <Button Content="{StaticResource AllRedIcon}"/>
   <Button Content="{StaticResource RedRectangle}"/>
   <Button Content="{StaticResource GreenRectangle}"/>
</ToolBar>

在设计器中看起来是这样的:

Toolbar with buttons in Designer mode

问题出在图标由 4 个矩形组成的按钮上。在运行时不会为这两个按钮呈现内容。

运行时看起来像这样:

Toolbar at runtime

AllGreenIcon 的代码:

<UserControl.Resources>

<Grid x:Key="AllGreenIcon" Height="16" Width="16" Effect="{StaticResource IconDropShadowEffect}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="0,0,1,1" Grid.Row="0" Grid.Column="0"/>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="1,0,0,1" Grid.Row="0" Grid.Column="1"/>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="0,1,1,0" Grid.Row="1" Grid.Column="0"/>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="1,1,0,0" Grid.Row="1" Grid.Column="1"/>
</Grid>


</UserControl.Resources>

有没有人知道我该如何解决这个问题? 提前致谢!

最佳答案

这个常见问题是由于 WPF(逻辑)要求每个 UIElement 都有一个父元素。在您的情况下,您正在向资源添加一个元素 - GreenRectangle,然后您将此元素用作 Content 用于您的多个 ContentControl AllGreenIcon 资源。每次将元素连接到可视化树时,它都会更改其父引用,这保证了元素在可视化树中只出现一次。 例如,所有绿色按钮都将使用相同的 GreenRectangle 元素实例。由于每次 GreenRectangle 连接到可视化树时,其父项都会更改,只有最后一个使用 GreenRectange 资源的项目才会实际显示该元素。

总而言之,避免在资源中声明和使用 UIElements。您应该使用 StyleControltemplate

注意:在您的解决方案中,资源中声明的AllGreenIcon 网格将有同样的问题- 不能同时在UI 的两个不同位置使用。请改用 ContentTemplate

例如:

<Button ContentTemplate="{StaticResource AllGreenIconTemplate}"/>

关于c# - 按钮自定义内容在运行时不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552812/

相关文章:

vb.net - 如何缩放表单上的控件以按比例适合表单?

c# - 为什么不经常使用无符号变量?

c# - 通过循环创建数组

c# - 哪种类型的可抛出错误适用于这种情况?

c# - 如何覆盖 [] 数组中的 ToString()?

c# - "x"最小化WinForm,右键菜单关闭WinForm?

wpf - 如何从可调整大小的窗口中删除最小化和最大化按钮?

c# - 如何像图像一样在 C# WPF 窗口中添加 svg/xaml 文件?

c# - MVVM:在 WPF NET 3.5 中完成线程池工作项后更新 View 的控件可见性

c# - 如何从mysql表中删除单个值