2016-10-08 63 views
0

我需要測量按鈕(和單選按鈕)的DesiredSize或ActualHeight/Width,但實際上並沒有將它放到可視化樹上,但我總是找回無意義的值。測量其他控件(如TextBlock)時,這種方法也適用。UWP XAML中的按鈕和單選按鈕的DesiredSize

 var button = new Button 
     { 
      Content = "Hello World", 
      FontSize = 15 
     }; 

     button.Measure(new Size(maxWidth, double.PositiveInfinity)); 
     var height = button.DesiredSize.Height; 
     var width = button.DesiredSize.Width 

我回來了21px的高度和0px的寬度。任何想法,爲什麼我回到寬度爲0?

回答

0

我需要測量一個按鈕(和單選按鈕)的DesiredSize或ActualHeight/Width,但實際上並沒有將它放到可視化樹上,但我總是找回無意義的值。

如果指定一個字符串值Button.Content,該值將通過在運行時,這之後會發生綁定被分配到裏面的TextBlock的Button.Measure(您可以通過添加按鈕的頁面中看到這一點,並檢查LiveProperty Explorer): enter image description here

所以你得到了錯誤的期望大小。

作爲一種變通方法,您可以創建一個TextBlock和這個TextBlock中分配給按鈕:

var tbContent = new TextBlock() 
{ 
    Text = "Hello World", 
    FontSize=15 
}; 
var button = new Button 
{ 
    Content = tbContent, 
}; 
var h= button.DesiredSize.Height; 
button.Measure(new Size(200, double.PositiveInfinity)); 
var height = button.DesiredSize.Height; 
var width = button.DesiredSize.Width; 

然後你會得到這個按鈕的正確尺寸。

+0

謝謝埃爾維斯!這樣可行! –

0

我猜這是不可能的。您在加載模板之前測量按鈕。

我只能建議做這樣的事情:

var but = new Button(); 
but.Content = "Hello"; 

var popup = new Popup(); 
popup.Child = but; 
popup.IsOpen = true; 
popup.Visibility = Visibility.Collapsed; 

but.Loaded += (s, e) => 
{ 
    System.Diagnostics.Debug.WriteLine(but.RenderSize); 
    popup.IsOpen = false; 
}; 

但它是一種哈克,按鈕將不會加載,直到以後的某個時間,使這可能是難以管理的整個過程異步的。