我有一个托管在 Windows 窗体窗体中的 UserControl
。在这个 UserControl
中,我有一个 ToolBar
,其中有各种按钮:
<ToolBar>
<Button Content="{StaticResource AllGreenIcon}"/>
<Button Content="{StaticResource AllRedIcon}"/>
<Button Content="{StaticResource RedRectangle}"/>
<Button Content="{StaticResource GreenRectangle}"/>
</ToolBar>
在设计器中看起来是这样的:
问题出在图标由 4 个矩形组成的按钮上。在运行时不会为这两个按钮呈现内容。
运行时看起来像这样:
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
。您应该使用 Style
和 Controltemplate
。
注意:在您的解决方案中,资源中声明的AllGreenIcon
网格将有同样的问题- 不能同时在UI 的两个不同位置使用。请改用 ContentTemplate
。
例如:
<Button ContentTemplate="{StaticResource AllGreenIconTemplate}"/>
关于c# - 按钮自定义内容在运行时不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552812/