在自定义ItemsControl中装饰项目,而不是使用ItemContainer

时间:2014-04-20 04:12:12

标签: wpf xaml itemscontrol itemtemplate itemcontainerstyle

我想创建(相当于)自定义ItemsControl,其中Item放在StackPanel中,与其他控件混合,比如{{1} }。所以,我希望以下内容在布局方面是等效的:

Button

<StackPanel>
    <Button>OK</Button>
    <TextBox>Hello</TextBox>
    <Button>OK</Button>
    <TextBox>World</TextBox>
</StackPanel>

我所关注的所有其他道路(<CustomControlInQuestion> <TextBox>Hello</TextBox> <TextBox>World</TextBox> </CustomControlInQuestion> s,ItemContainer s,自定义ItemTemplate s)都未能创造出这种行为。有没有什么技术可以实现这个目标?

可能值得强调的是,我确实需要将其作为自定义控件:)

谢谢!

2 个答案:

答案 0 :(得分:0)

您好我只是提示您达到您的要求,如果您熟悉ItemTemplateSelector, dataTemplate你可以自己做。

<ItemsControl x:Name="PanelControl" ItemsSource="{Binding bindYourSourceHere}" 
    ItemTemplateSelector="{StaticResource bindYourItemTemplateSelector}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
</ItemsControl>


//StackPanel is set to ItemsControl.ItemsPanel
// Write a ItemTemplateSelector and write your own logic to select either button template or textbox template
// In case if I misunderstood your requirement, please let me know it in more detail.

答案 1 :(得分:0)

这可能是一个起点,一个垂直堆栈面板的迷你实现:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace TabControl1
{
    public class CustomControl1 : Panel
    {
        protected override Size MeasureOverride (Size availableSize)
        {
            Size panelDesiredSize = new Size (0, 0);

            foreach (UIElement child in this.InternalChildren)
            {
                var childMaxSize = new Size (double.PositiveInfinity, double.PositiveInfinity);
                child.Measure (childMaxSize);
                var v = (FrameworkElement)child;

                panelDesiredSize.Width += child.DesiredSize.Width;

                if (panelDesiredSize.Height < child.DesiredSize.Height)
                {
                    panelDesiredSize.Height = child.DesiredSize.Height;
                }
            }

            return panelDesiredSize;
        }

        protected override Size ArrangeOverride (Size finalSize)
        {
            double x = 0;
            double y = 0;

            foreach (UIElement child in this.InternalChildren)
            {
                child.Arrange (new Rect (new Point (x, y), child.DesiredSize));

                x += child.DesiredSize.Width;
            }

            return finalSize; // Returns the final Arranged size
        }
    }
}