0

我为我的自定义面板声明了一个附加属性:

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);
}

如果我将面板定义为:

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

但是,如果我将此面板用作ItemsPanelTemplatea ListBox,它总是返回默认值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>

我还注意到,当在 a 中使用自定义包装面板时ListBox,它会发送double.PositiveInfiniteArrange 方法,因此 Arrange 永远无法设置值。单独使用时同样有效

谢谢

4

1 回答 1

0

即使我尝试了同样的方法,但它在其他一些面板形式中对我不起作用,我想设置网格但它不起作用。

问题是,由于 ListBox 只能将 ListBoxItem 作为其真正的逻辑子项,而不是任何 Button 等,因此当您在 ListBox 的内容窗格中添加 Button 或任何项目时,当它执行时,ItemsPanel 将具有其直接子项作为 ListBoxItem 和 ListBoxItem 的内容将成为您添加的控件。

所以在运行时这将是你的可视化树......

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

这就是您的附加属性不起作用的原因。

解决方案是,您尝试将 ItemContainerStyle 中的 ListBoxItem 属性设置为 DataContext 的 WeightedPanel.Weight。我知道它令人困惑。

或者

您可以将 ListBoxItem 添加为子项.. 喜欢

<ListBox>
     <ListBox.ItemsPanel>
          <ItemsPanelTemplate>
                <local:WeightedPanel />
            </ItemsPanelTemplate>        
      </ListBox.ItemsPanel>
    <ListBoxItem local:WeightedPanel.Weight="4"><Button/></ListBoxItem>
    <ListBoxItem local:WeightedPanel.Weight="4"><Button/></ListBoxItem>
</ListBox>
于 2009-10-06T06:41:42.997 回答