WPF - Window, UserControl 클래스 상속
WPF 응용 프로그램을 만들 때도 역시, 상속을 통해 기본적인 기능을 갖는 기반 클래스를 정의해서 처리하는 것이 좋습니다. 하지만, WinForm과 비교해서 약간 다른 상속처리를 하게 되죠.
예를 들어, Window를 다음과 같이 정의하는 경우,
public partial class MainShell : WindowBase // 보통은 Window
{
}
코드 파일에서만 위와 같이 변경해 주면 다음과 같은 오류가 발생합니다.
D:\...\Shell.xaml.cs(22,26): error CS0263:
Partial declarations of 'Shell.MainShell' must not specify different base classes
이유인 즉, shell.xaml 자체를 빌드할 때 생성되는 임시 C# 파일에는 다음과 같은 정의를 포함하고 있기 때문입니다.
----- shell.g.cs -------
public partial class MainShell : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 8 "..\..\Shell.xaml"
internal System.Windows.Controls.Button button1;
#line default
#line hidden
private bool _contentLoaded;
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
; ... [이하 생략] ...
오호... XAML 자체가 partial 타입으로 나오면서 생성되는 임시 코드 파일에는 여전히 "System.Windows.Window"로 되어 있기 때문이군요. 해결 방법은 의외로 간단하지요. 아래의 토픽에서도 이를 소개해 주고 있습니다.
WPF: Inheriting from custom class instead of Window
; http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx
그렇군요. xaml 파일 자체도 아래와 같이 새로운 WindowBase를 사용하도록 설정해주면 되는 것이었습니다.
<baseClass:WindowBase x:Class="Shell.MainShell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:baseClass="clr-namespace:Test.Core;assembly=Test.Core">
<Grid>
<Button Name="button1" Click="button1_Click">Button</Button>
</Grid>
</baseClass:WindowBase>
마지막으로, 위의 변화가 반영된 shell.g.cs 임시 파일을 확인해 보면,
public partial class MainShell : Test.Core.WindowBase, System.Windows.Markup.IComponentConnector {
#line 8 "..\..\Shell.xaml"
internal System.Windows.Controls.Button button1;
#line default
#line hidden
private bool _contentLoaded;
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
; ... [이하 생략] ...
원하는 결과가 반영이 되었습니다. 마찬가지로 이와 동일한 방식으로 UserControl에 대한 상속도 처리해 줄 수 있습니다.
맺기 전에... 사실, 이 부분은 약간 아쉽긴 하죠. 어차피 partial 클래스이기 때문에, 굳이 XAML 파일에서 생성되는 임시 g.cs 파일에서 기반 클래스를 명시해 줄 필요는 없습니다. 아마도, 이 부분은 언젠가는 개선되지 않을까 싶네요. ^^
[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]