2013-10-18 52 views
1

我偶然發現了WPF中的一些有趣的事情,我無法向自己解釋這一點。爲什麼孩子測量仍然工作,而父母崩潰?

它是一種奇怪的行爲。

標題基本上解釋了一切。

下面是一個例子,我設置了Grid.Visibility到Collapsed,並且我在該Grid內控制了一個控件的度量。即使認爲它不應該被重新測量,因爲在wpf控件中不可見的控件沒有被測量。

public class MyControl : Button 
{ 
    public MyAnotherControl AnotherControl 
    { 
     get; 
     set; 
    } 

    public Grid Grid 
    { 
     get; 
     set; 
    } 

    protected override Size MeasureOverride(Size constraint) 
    { 
     base.MeasureOverride(constraint); 
     return new Size(100, 20); 
    } 

    protected override Size ArrangeOverride(Size arrangeBounds) 
    { 
     base.ArrangeOverride(arrangeBounds); 
     return arrangeBounds; 
    } 

    protected override void OnClick() 
    { 
     Grid.Visibility = Visibility.Collapsed; 
     AnotherControl.InvalidateMeasure(); 
     base.OnClick(); 
    } 
} 

這是我在Grid中的另一個控件。

public class MyAnotherControl : Button 
{ 
    protected override Size MeasureOverride(Size constraint) 
    { 
     base.MeasureOverride(constraint); 
     Console.WriteLine("Measure called"); 
     return new Size(100, 10); 
    } 

    protected override Size ArrangeOverride(Size arrangeBounds) 
    { 
     base.ArrangeOverride(arrangeBounds); 
     return arrangeBounds; 
    } 
} 

這是XAML:

<Grid> 
     <StackPanel> 
      <local:MyControl Background="Blue" Grid="{x:Reference grid}" AnotherControl="{x:Reference anotherControl}"/> 
      <Grid x:Name="grid"> 
       <local:MyAnotherControl Content="{Binding}" Background="Red" x:Name="anotherControl"/> 
      </Grid> 
     </StackPanel> 
    </Grid> 

正如你所看到的OnClick我改變Grid.Visibility和無效網格的內部控制措施。

根據MSDN:

元素,其中可視性是不可見的不參與輸入事件(或命令),不影響任一測量或排列布局的通行證,不是在一個標籤序列,並且將不會在命中測試中報告。

http://msdn.microsoft.com/en-us/library/system.windows.uielement.visibility.aspx

的問題是爲什麼MyAnotherControl被當它不應該衡量?

如果我將代碼更改爲從開始摺疊的網格,則在使度量失效時,MyAnotherControl不再被重新測量。這代表正確的wpf行爲。

<Grid> 
     <StackPanel> 
      <local:MyControl Background="Blue" Grid="{x:Reference grid}" AnotherControl="{x:Reference anotherControl}"/> 
      <Grid x:Name="grid" Visibility="Collapsed"> 
       <local:MyAnotherControl Content="{Binding}" Background="Red" x:Name="anotherControl"/> 
      </Grid> 
     </StackPanel> 
    </Grid> 

這似乎是不同的,你是否設置可視性權限從開始或不。

任何想法?我非常感謝你的建議和想法。

+0

喜@ DEV-刺蝟,我認爲這是從時間農作物多達時間的語義正確的錯誤行爲實例之一:MyAnotherControl的知名度是可見的,所以被列入測量等,但是當網格被摺疊時,MyAnotherControl可見性保持不變,因此仍然可見,所以即使沒有看到它,也可以測量它,因爲它的包含父元素被摺疊並且不能看到實際內容,但它仍然存在....排序隱形對象來測試和嘗試你的耐心。 – GMasucci

+0

從上面繼續: 無法測試這更多,直到我回到我的開發機器的家,但讓我知道,我可以回覆你 – GMasucci

+0

@GMasucci很確定你是正確的。 Visiblity不會繼承。你可以做的最好的事情是走上視覺樹,這是一個灰色的代碼來證明。請注意,不會在未顯示的元素上調用OnRender()。 – Gusdor

回答