Question

I am wanting to expose a Style as a dependency property. Basically there is a rectangle indicator in the middle and the using control is going to expose a style dependency property for containing controls to set. It would allow those containing controls to provide a style for coloring based on their own knowledge of their items.

<ItemsControl ItemsSource="{Binding Rows}">
   <ItemsControl.ItemTemplate>
       <DataTemplate>
           <StackPanel Orientation="Horizontal">
               <TextBlock Text="{Binding RowName}"/>
               <ItemsControl ItemsSource="{Binding Statuses}">

                    <Rectangle Style="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Path=RectangleStyle}"/>
               </ItemsControl>
           </StackPanel>
       </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

The dependency property in the code-behind of the custom control.

    public Style RectangleStyle
    {
        get { return (Style)GetValue(RectangleStyleProperty); }
        set { SetValue(RectangleStyleProperty, value); }
    }

    public static readonly DependencyProperty RectangleStyleProperty =
        DependencyProperty.Register("RectangleStyle", typeof(Style), typeof(MyControl), new PropertyMetadata(null));

This would then be used like:

    <MyControl>
        <MyControl.RectangleStyle>
            <Style TargetType="{x:Type Rectangle}">
                <Setter Property="Fill" Value="Red"/>
            </Style>
        </MyControl.RectangleStyle>
    </MyControl>

This is not working at all and I'm not sure if my approach is even correct.

Was it helpful?

Solution

Stupid syntax error. I needed to set the ItemsTemplate for the Inner ItemsControl. I was setting the content of the ItemsControl to be the Rectangle.

<ItemsControl ItemsSource="{Binding Rows}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding RowName}"/>
                <ItemsControl ItemsSource="{Binding Statuses}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Rectangle Style="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Path=RectangleStyle}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top