0

我想创建(相当于)一个自定义ItemsControl,其中Items 放置在 a 中StackPanel,与其他一些控件混合,比如 a Button。所以,我希望以下在布局方面是等效的:

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

<CustomControlInQuestion>
    <TextBox>Hello</TextBox>
    <TextBox>World</TextBox>
</CustomControlInQuestion>

我走的所有替代道路(ItemContainers,ItemTemplates,custom Panels)都未能产生这种行为。有没有什么技术可以做到这一点?

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

谢谢!

4

2 回答 2

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.
于 2014-04-20T09:00:04.053 回答
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
        }
    }
}
于 2014-04-20T09:42:53.873 回答