加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:29:39 所属栏目:百科 来源:网络整理
导读:我有一个以 Windows窗体形式托管的UserControl.在这个UserControl中我有一个ToolBar,我有各种按钮: ToolBar Button Content="{StaticResource AllGreenIcon}"/ Button Content="{StaticResource AllRedIcon}"/ Button Content="{StaticResource RedRectangl
我有一个以 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}"/>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读