微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

在desinger中看起来像这样:

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,1,1" Grid.Row="0" Grid.Column="0"/>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="1,1" Grid.Row="0" Grid.Column="1"/>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="0,0" Grid.Row="1" Grid.Column="0"/>
    <ContentControl Content="{StaticResource GreenRectangle}" Margin="1,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}"/>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐