c# - ContentPresenter 而不是 UserControl 被添加到我的自定义面板
问题描述
我创建了一个继承自 Canvas 的自定义面板。我想用它在 ItemsControl 中查看我的用户控件。
这是我的 XAML:
<ItemsControl ItemsSource="{Binding Groups}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<c:MyCustomPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<ItemContainerTemplate>
<app:MyUserControl Margin="5" MinWidth="200"/>
</ItemContainerTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如您所见,我的用户控件将 MinWidth 设置为 200。
现在,在我的自定义面板中,覆盖了 ArrangeOverride 方法:
protected override Size ArrangeOverride(Size arrangeSize)
{
foreach (UIElement obj in InternalChildren)
{
//some other code
}
return arrangeSize;
}
问题是由于某种原因 InternalChildren 由 ContentPresenter 项目而不是我的用户控件组成。当然,在每个 ContentPresenter 中都有我的用户控制,但这不是我想要的。我需要在这里读取我的 userControl 的 MinWidth,但是我从 ContentPresenter 中读取它(始终为 0)。
当我做非常简单的测试时:
<ItemsControl ItemsSource="{Binding Buttons}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<c:MyCustomPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
其中 Buttons 只是 Button 控件的列表,一切都按预期工作。所以我认为问题可能出在我使用 ItemsControl 的方式上。但不知道如何修复它。
解决方案
在 ItemContainerStyle 中设置 ContentPresenter 的 MinWidth 属性:
<ItemsControl ItemsSource="{Binding Groups}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<c:MyCustomPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<app:MyUserControl Margin="5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="MinWidth" Value="200"/>
</Style >
</ItemsControl.ItemContainerStyle>
</ItemsControl>
推荐阅读
- html - 使用 flex 和 css 网格制作响应式布局
- python - OpenCV 无法连接到 X 服务器
- arrays - 如何在 mongo db 聚合中将数据作为数组获取
- excel - 检查多列,如果发现它从一个单元格返回数据
- php - PHP 启动:无法加载动态库 'pdo_mysql'
- android - 在 Flutter 中打开屏幕时如何使应用程序屏幕出现
- java - 在 java 中使用 thymleaf html 模板下载 pdf 文件时,css 样式不可见
- database - Flutter:自动更新数据
- javascript - Typescript 在 json 中使用枚举
- android - 如何将图像的宽度设置为 imageView android