Wpf Attach属性未返回该值

Wpf Attach属性未返回该值,wpf,attached-properties,Wpf,Attached Properties,我为自定义面板声明了一个附加属性: public static readonly DependencyProperty WeightProperty = DependencyProperty.RegisterAttached( "Weight", typeof(double), typeof(WeightedPanel), new FrameworkPropertyMetadata(1.0, Framewo

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

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>
如果我将面板定义为:

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>
我还注意到,当在列表框中使用自定义包装面板时,它会在Arrange方法中发送double.PositiveInfinite,因此Arrange永远无法设置值。单独使用时,同样的方法也可以很好地工作


谢谢

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

问题是,由于ListBox只能将ListBoxItem作为其真正的逻辑子项,而不是任何按钮等,当您在ListBox的内容窗格中添加按钮或任何项时,当它执行时,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>

阿卡什,很好的解释。我知道Listbox使用listboxitem作为其项目的演示者。我不同意的地方是,attach属性将自己附加到每个元素。由于我将属性附加到button not ListBoxItem,因此无法获取值。您是否可以在建议使用ItemContainerStyle的地方详细介绍您给出的第一个解决方案。第二个解决方案非常有效。万分感谢