簡體   English   中英

ContentPresenter而不是UserControl已添加到我的自定義面板

[英]ContentPresenter instead of UserControl is added to my custom panel

我創建了一個從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>

問題是由於某種原因,InternalChildren包含ContentPresenter項而不是我的用戶控件。

這是因為ItemsControl會將所有項目包裝在ContentPresenter除非它們是UIElements 如果綁定到UIElements的集合(例如Buttons ,則不會創建ContentPresenter ,但也不會應用ItemTemplate

您可以按照@Clemens的建議設置ContentPresenter容器的MinWidth ,也可以通過實現自己的自定義ItemsControl並覆蓋GetContainerForItemOverride()IsItemItsOwnContainerOverride()方法來阻止ContentPresenters創建:

public class MyItemsControl : System.Windows.Controls.ItemsControl
{
    protected virtual DependencyObject GetContainerForItemOverride()
    {
        return new MyUserControl();
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return (item is MyUserControl);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM