WPF Base Control 設計要項

  • 2804
  • 0
  • 2012-03-17

WPF Base Control 設計要項

在 WPF 程式新增一個 UserControl 時, 預設是繼承自 System.Windows.Controls.UserControl,

若將父層換為自己所撰寫的類別, Base Control 程式碼如下:

namespace WpfControlBase
{
    public class ControlBase : UserControl
    {
        public System.Windows.Window ParentWindow { get; set; }
    }
}

 

在繼承的 UserControl 中有兩個步驟

1. C# 或 VB 檔案中, UserControl 中繼承此類別

public partial class UserControl1 : WpfControlBase.ControlBase 
{

}

 

2. 修改 xaml 檔案的宣告

<WpfCB:ControlBase x:Class="CloseShowDialog.UserControl1"
             xmlns:WpfCB="clr-namespace:WpfControlBase;assembly=WpfControlBase" >

 

筆者有個案例是, 在 UserControl 中要關閉視窗, 透過 Parent 找不到 Windows 物件,

暫時想到的解決方法是, 每一次動態載入UserControl 時, 透過 BaseControl 將視窗傳入,

後續要關閉視窗就由此屬性進行。

download code

 

以上是參考 <這篇> 討論.