首页 > 解决方案 > 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 的方式上。但不知道如何修复它。

标签: c#wpfcustom-controlsitemscontrol

解决方案


在 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>

推荐阅读