2009-10-05 55 views
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> 

但是,如果使用此面板爲ItemsPanelTemplateListBox,它始終返回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> 

我還注意到,當自定義畫布面板是在ListBox使用的,它在排列方法發送double.PositiveInfinite,因此安排是從來沒有能夠設置的值。精細同樣的作品全部由自己使用

感謝

回答

0

時即使我嘗試相同的,它在其它一些面板形式沒有工作對我來說,我想設置網格,但它沒有工作。

問題是,由於ListBox只能將ListBoxItem作爲其真實的邏輯子元素,而不是任何Button等,所以當您在ListBox的內容窗格中添加Button或任何項目時,ItemsPanel將其子項作爲ListBoxItem並且ListBoxItem的內容將成爲您添加的控件。

所以在運行時,這將是你的視覺樹...

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

這是你的附加屬性是不工作的原因。

解決方法是,您嘗試將ItemContainerStyle中的ListBoxItem屬性設置爲DataContext的WeightedPanel.Weight。我知道它令人困惑。

OR

您可以添加一個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> 
+0

阿卡什, 很能說明問題。我知道Listbox使用listboxitem作爲它的項目的主持人。我離開的地方是附屬屬性附加到每個元素的事實。因爲我將屬性附加到按鈕(而不是ListBoxItem),所以我無法獲取值。您能否詳細說明您在建議使用ItemContainerStyle時給出的第一個解決方案。第二個解決方案很好。太感謝了 – Sheraz 2009-10-06 13:24:08