WPF Canvas做自动缩放时获取控件的实际高度

        WPF在 Canvas控件,因为要实现自动缩放,高度和款第都是设置为自动的。如果用ActualWidth和ActualHeight返回的值都是零。

解决方法:

我们Loaded方法等程序加载完成之后再获取实际高度和宽度。

   

Loaded:在元素已布局、已呈现且可用于交互时发生。
1 <Window x:Class="Smoke.Weather.Main"
2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Window_Loaded"
4         Title="Main" Height="300" Width="300">
5     <Canvas x:Name="Carrier"  Background="Transparent"   >
6 
7     </Canvas>
8 </Window>

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Windows;
 6 using System.Windows.Controls;
 7 using System.Windows.Data;
 8 using System.Windows.Documents;
 9 using System.Windows.Input;
10 using System.Windows.Media;
11 using System.Windows.Media.Imaging;
12 using System.Windows.Shapes;
13 
14 namespace Smoke.Weather
15 {
16     /// <summary>
17     /// Main.xaml 的交互逻辑
18     /// </summary>
19     public partial class Main : Window
20     {
21         public Main()
22         {
23             InitializeComponent();
24         }
25 
26         private void Window_Loaded(object sender, RoutedEventArgs e)
27         {
28             Button  Spirit = new Button();
29             Spirit.Width = Carrier.ActualWidth;
30             Spirit.Height = Carrier.ActualHeight;
31             Carrier.Children.Add(Spirit);
32         }
33     }
34 }

 

posted @ 2014-11-27 09:39  _Dawn  阅读(3406)  评论(0编辑  收藏  举报