2009-11-18 127 views

回答

7

我不確定這會起作用,但是如果您註冊SizeChanged事件的處理程序,並且在那裏放入代碼,請保持寬高比爲1:1。

SizeChangedEventArgs參數具有舊的大小和新的大小,因此您可以檢查哪些已更改並相應地更新其他大小。

您可能需要引入一個保護變量,以便在更新HeightWidth時不會得到級聯的SizeChanged事件。

+0

我想調整大小時,控件將閃爍。 – 2009-11-18 12:35:31

+0

它不會閃爍,因爲WPF使用保留模式並以較低優先級完成渲染,所以渲染將看到所有「SizeChanged」事件的最終結果。例外:如果你的Window是'SizeToContent'並且它的大小受到影響,'SetWindowPos()'在計算過程中被立即調用,所以你可能會看到一些東西。 – 2009-11-19 09:22:32

-2
private bool isSizeChangeDefered; 

private void uiElement_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
     //Keep Acpect Ratio 
     const double factor = 1.8; 
     if(isSizeChangeDefered) 
      return; 

     isSizeChangeDefered = true; 
     try 
     { 
      if (e.WidthChanged) 
      { 
       driverPan.Height = e.NewSize.Width * factor; 
      } 
      if (e.HeightChanged) 
      { 
       driverPan.Height = e.NewSize.Width/factor; 
      } 
     } 
     finally 
     { 
     // e.Handled = true; 
      isSizeChangeDefered = false; 
     } 
    } 

也許這可以幫助...乾杯

+1

這個答案基本上是18個月前ChrisF提供的答案的一個例子。它也似乎不完整(什麼是driverPan變量?),我相信它有一個邏輯問題,如果在同一事件中改變高度/寬度(調整對角線大小) – 2011-05-05 22:51:01

3

嘗試使用視框和Stretch屬性設置爲統一

3

另一種選擇:

<local:MyControl Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/> 
+0

這對我來說完美,似乎是最簡單的答案(雖然我真的不明白它在做什麼)。 – brianberns 2016-03-30 04:45:48

+1

@brianberns它將'Width'屬性綁定到'ActualHeight'屬性。但是「實際高度」是什麼?一個RelativeSource!和_什麼相對來源? (本身!也就是說,我在說「我希望我自己的寬度是任何ActualHeight佈局系統爲我計算的」。 – heltonbiker 2016-03-30 15:57:00

+0

謝謝,這是有道理的。順便說一句,我發現這個解決方案的一個問題:如果只有主窗口的寬度發生變化(例如通過拖入或拖出右邊框),控件不知道調整大小,因爲它的高度沒有改變。 – brianberns 2016-03-31 14:45:37

0

我用這個代碼保持方面比率

在usercontrol全局定義org_width,org_height,org_rat IO:

private static double org_width = 77.6;//desired width 
private static double org_height = 81.4;//desired height 

private static double org_ratio = org_width/org_height; 

使用此代碼內部用戶控件在SizeChanged事件:

FrameworkElement UCborder = this; 
UCborder.Width = UCborder.Height*org_ratio; 

最終用戶控件的代碼應該看起來像這樣:

using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Input; 
using System.Windows.Media; 

namespace yournamespace 
{ 
    public partial class YourUserControl : UserControl 
    { 

     private static double org_width = 77.6;//desired width 
     private static double org_height = 81.4;//desired height 

    private static double org_ratio = org_width/org_height; // width/height 



    public YourUserControl() 
    { 
     InitializeComponent(); 
    } 


    private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
      FrameworkElement UCborder = this; 
      UCborder.Width = UCborder.Height*org_ratio; 
    } 
    } 
} 

好運

相關問題