首页 / C# / c# – 按钮自定义内容在运行时不呈现
c# – 按钮自定义内容在运行时不呈现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 按钮自定义内容在运行时不呈现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1970字,纯文字阅读大概需要3分钟。
内容图文
![c# – 按钮自定义内容在运行时不呈现](/upload/InfoBanner/zyjiaocheng/773/9d0a1ed0f66d491b93a70d7228816b15.jpg)
我有一个以Windows窗体形式托管的UserControl.在这个UserControl中我有一个ToolBar,我有各种按钮:
<ToolBar>
<Button Content="{StaticResource AllGreenIcon}"/>
<Button Content="{StaticResource AllRedIcon}"/>
<Button Content="{StaticResource RedRectangle}"/>
<Button Content="{StaticResource GreenRectangle}"/>
</ToolBar>
在desinger中看起来像这样:
问题在于图标由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>
有没有人有一些想法我怎么能解决这个问题?
提前致谢!
解决方法:
这个常见问题是由于每个UIElement的WPF(逻辑)要求具有单个父级.在您的情况下,您将向资源添加一个元素 – GreenRectangle,然后您将此元素用作AllGreenIcon资源中多个ContentControl的内容.每次将元素连接到可视树时,它将更改其父引用,这保证元素在可视树中仅存在一次.
例如,所有绿色按钮都将使用相同的GreenRectangle元素实例.由于每次将GreenRectangle连接到可视树时,其父级都会被更改,因此只有使用GreenRectange资源的最后一项才会实际显示该元素.
总之,避免在资源中声明和使用UIElements.您应该使用Styles和Controltemplates.
注意:在您的解决方案中,资源中声明的AllGreenIcon网格将具有相同的问题 – 不能同时在UI中的两个不同位置使用.请改用ContentTemplate.
例如:
<Button ContentTemplate="{StaticResource AllGreenIconTemplate}"/>
内容总结
以上是互联网集市为您收集整理的c# – 按钮自定义内容在运行时不呈现全部内容,希望文章能够帮你解决c# – 按钮自定义内容在运行时不呈现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。