creating custom itemscontrol

后端 未结 1 993
时光说笑
时光说笑 2021-02-03 14:24

I\'m trying to create a custom control derived from ItemsControl. The ItemsControl is initialized with items, but they are not shown.

t

相关标签:
1条回答
  • 2021-02-03 15:08

    You need to set the ItemsSource. So, for example, you could add ItemsSource = Checkers; below the last Checkers Add line. Even though you're trying to set the ItemsSource to Checkers in the style, I think it would be easier if you set in the control class. Just my two cents, though.

    Here's an example of the PipeControl class:

    public class PipeControl : ItemsControl
    {
        public ObservableCollection<Checker> Checkers { get; set; }
        static PipeControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(PipeControl), new FrameworkPropertyMetadata(typeof(PipeControl)));
        }
        public PipeControl()
        {
            Checkers = new ObservableCollection<Checker>();
            Checkers.Add(new Checker());
            Checkers.Add(new Checker());
            Checkers.Add(new Checker());
            Checkers.Add(new Checker());
            Checkers.Add(new Checker());
            ItemsSource = Checkers;
        }
    }
    

    You also need an ItemsPresenter in your ControlTemplate and your Ellipse needs a width and height. Here's an updated style for you:

    <Style TargetType="{x:Type local:PipeControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:PipeControl}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <ItemsPresenter />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate DataType="{x:Type local:Checker}">
                    <Ellipse Width="25"
                             Height="25"
                             HorizontalAlignment="Stretch"
                             VerticalAlignment="Stretch"
                             Fill="Red" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
    0 讨论(0)
提交回复
热议问题