Question

I have an attached property declared for my custom panel as:

public static readonly DependencyProperty WeightProperty = DependencyProperty.RegisterAttached(
        "Weight", typeof(double), typeof(WeightedPanel),
                new FrameworkPropertyMetadata(1.0, 
                    FrameworkPropertyMetadataOptions.AffectsParentMeasure |
                    FrameworkPropertyMetadataOptions.AffectsParentArrange ));

public static void SetWeight(DependencyObject obj, double weight)
{
    obj.SetValue(WeightProperty, weight);
}

public static double GetWeight(DependencyObject obj)
{
    return (double) obj.GetValue(WeightProperty);
}

It works fine if I define the panel as:

<local:WeightedPanel Grid.Row="0" Height="200">
    <Button local:WeightedPanel.Weight="8" />
    <Button local:WeightedPanel.Weight="2"/>
</local:WeightedPanel>

But if I use this panel as ItemsPanelTemplate for a ListBox, it always returns the default value in ArrangeOverride.

<ListBox Grid.Row="2" Height="100">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <local:WeightedPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <Button local:WeightedPanel.Weight ="6" />
    <Button local:WeightedPanel.Weight ="4"/>
</ListBox>

I also noticed that when the custom wrap panel is used in a ListBox, it sends double.PositiveInfinite in Arrange method and therefore Arrange is never able to set the values. The same works fine when used all by itself

Thanks

Was it helpful?

Solution

Even i tried same and it didnt work for me in some other panel form, I wanted to setup grid but it didnt work.

The problem is, since ListBox can have only ListBoxItem as its real logical child, not any Button etc, when you add Button or any item in ListBox's content pane, when it executes, the ItemsPanel will have its immediate children as ListBoxItem and ListBoxItem's content will be the control you added.

So at runtime this will be your visual tree...

ItemsControl (ListBox)
     ItemsPanel (WeightedPanel)
          ListBoxItem
              Button
          ListBoxItem
              Button...

This is the reason your attached property is not working.

The solution would be, you try to set ListBoxItem's property in the ItemContainerStyle to be of DataContext's WeightedPanel.Weight. I know its confusing.

OR

You can add ListBoxItem as child.. like

<ListBox>
     <ListBox.ItemsPanel>
          <ItemsPanelTemplate>
                <local:WeightedPanel />
            </ItemsPanelTemplate>        
      </ListBox.ItemsPanel>
    <ListBoxItem local:WeightedPanel.Weight="4"><Button/></ListBoxItem>
    <ListBoxItem local:WeightedPanel.Weight="4"><Button/></ListBoxItem>
</ListBox>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top