Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 10개 있습니다.)
.NET Framework: 388. 일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법
; https://www.sysnet.pe.kr/2/0/1508

.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제
; https://www.sysnet.pe.kr/2/0/11106

.NET Framework: 678. 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

.NET Framework: 715. C# - Windows 10 운영체제의 데스크톱 앱에서 TTS(SpeechSynthesizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11412

.NET Framework: 722. C# - Windows 10 운영체제의 데스크톱 앱에서 음성인식(SpeechRecognizer) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11420

.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11799

.NET Framework: 852. WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법
; https://www.sysnet.pe.kr/2/0/12001

.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출
; https://www.sysnet.pe.kr/2/0/12470

닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
; https://www.sysnet.pe.kr/2/0/13438




WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법

이전에 데스크톱 응용 프로그램에서 UWP 구성 요소를 사용하는 방법을 설명했었습니다.

데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법
; https://www.sysnet.pe.kr/2/0/11284

윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기
; https://www.sysnet.pe.kr/2/0/11073

이번에는 아래의 질문 글에 따라,

안녕하세요. WPF에서 UWP Control을 참조하려고 합니다.
; https://www.sysnet.pe.kr/3/0/5099

UWP UI 컨트롤을 WPF에 포함하는 방법을 알아보겠습니다. 사실 방법은, 위의 질문자가 써놓았던 다음의 자료에서 잘 설명하고 있습니다.

WindowsXamlHost control for Windows Forms and WPF
; https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/windowsxamlhost

그래도 ^^ 한번 직접 따라 해 보겠습니다. 우선, .NET Framework 4.6.2 이상의 WPF 프로젝트(WinForm의 경우에는 이 글에서 예제로 실습하진 않지만 방식은 유사하므로 이 글을 읽고 나서 위의 문서를 보시면 바로 알 수 있습니다.)를 하나 만들고 NuGet 패키지 참조를 추가합니다.

Install-Package Microsoft.Toolkit.Wpf.UI.XamlHost 

그다음 아래의 외부 모듈을 참조 추가하고,

C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd

"View" / "Toolbox (Ctrl + Alt + X)"를 열면 "Windows Community Toolkit" 범주에 "WindowsXamlHost" 컨트롤을 WPF XAML Form에 끌어다 놓습니다. 그럼 XAML에 WindowsXamlHost 마크업이 추가되는데 기본 추가된 속성을 대충 정리하면 다음과 같이 XAML이 구성될 것입니다.

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:XamlHost="clr-namespace:Microsoft.Toolkit.Wpf.UI.XamlHost;assembly=Microsoft.Toolkit.Wpf.UI.XamlHost" x:Class="WpfApp1.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>

        <XamlHost:WindowsXamlHost />

    </Grid>
</Window>

이제 원하는 UWP 컨트롤을 WindowsXamlHost의 InitialTypeName 속성으로 지정하면 됩니다. 질문 글에 포함된 예제에서는 UWP Button 컨트롤을 지정하고 있습니다.

<XamlHost:WindowsXamlHost x:Name="btnTest" InitialTypeName="Windows.UI.Xaml.Controls.Button" />

이후, UWP 래퍼 컨트롤 내에서 InitialTypeName에 지정한 컨트롤을 생성할 텐데 이 컨트롤은 다음과 같이 Child 속성으로 접근할 수 있습니다.

using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Windows.UI.Xaml.Controls.Button button = btnTest.Child as Windows.UI.Xaml.Controls.Button;
            button.Content = "TEST";
            button.Click += Button_Click;
        }

        private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            MessageBox.Show("TestButton Clicked");
        }
    }
}

하지만 실제로 실행해 보면 위의 코드는 TargetInvocationException / NullReferenceException 오류가 발생합니다.

System.Reflection.TargetInvocationException
  HResult=0x80131604
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
...[생략]...
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at WpfApp1.App.Main()

Inner Exception 1:
NullReferenceException: Object reference not set to an instance of an object.

왜냐하면 UWP 래퍼 컨트롤 내에서 내부 컨트롤을 생성할 시간이 필요한데, 위의 코드는 생성되기도 전에 Child 속성에 접근했기 때문입니다. 다행히 UWP 래퍼 컨트롤은 내부 컨트롤을 생성한 시점을 이벤트로 알려주는데요, 그래서 대개의 경우 다음과 같이 XAML 코드를 만들어 주면 됩니다.

<XamlHost:WindowsXamlHost x:Name="btnTest" InitialTypeName="Windows.UI.Xaml.Controls.Button" 
                            ChildChanged="ChildControlCreated" />

그리고 저 이벤트 핸들러 이후의 시점부터 Child 속성을 안전하게 접근할 수 있습니다.

using System;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ChildControlCreated(object sender, EventArgs e)
        {
            Windows.UI.Xaml.Controls.Button button = btnTest.Child as Windows.UI.Xaml.Controls.Button;
            button.Content = "TEST";
            button.Click += Button_Click;
        }

        private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            MessageBox.Show("TestButton Clicked");
        }
    }
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)

질문 글 덕분에 저도 이렇게 실습을 해보는군요. ^^




참고로, 이 기능은 12월에 릴리스된 Windows 1809 업데이트부터 사용할 수 있다고 문서에 명시되어 있습니다.

Starting in Windows 10 Insider Preview SDK build 17709

현재(2018-12-19 기준) 일반 사용자들에게 배포된 Windows 10은 Version 1803에 OS Build 번호가 17134입니다. 만약, 1803 이하의 윈도우 10에서 위의 예제 코드를 실행한다면 MainWindow 로드 시에 다음과 같은 예외가 발생합니다.

System.Windows.Markup.XamlParseException
  HResult=0x80131501
  Message='The invocation of the constructor on type 'Microsoft.Toolkit.Wpf.UI.XamlHost.WindowsXamlHost' that matches the specified binding constraints threw an exception.' Line number '12' and line position '10'.
  Source=PresentationFramework
  StackTrace:
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)

Inner Exception 1:
TypeLoadException: Could not find Windows Runtime type 'Windows.UI.Xaml.Hosting.DesktopWindowXamlSource'.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/9/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2018-12-31 10시07분
[WPF] 정말 감사합니다. 그런데 XamlHost로 만든 UWP Control은 WPF Control 보다 항상 위에 있고, WPF Canvas 위에 올려놓고 해당 Canvas를 Storyboard로 애니메이션을 줘도 먹질 않던데 이건 해결 방법이 없을까요?

사실 제가 원하는건 Win2D를 WPF에서 쓰는건데 .NET Core 3.0에선 가능하다고 합니다. 그런데 문제는 제가 Win2D CanvasAnimatedControl을 바닥에 깔아놓고 그 위에 몇가지 Button, DataGrid 등을 놓을 예정이라서요...
[guest]
2018-12-31 11시59분
XamlHost를 자세히는 안 봤지만, 아마도 "Window"를 가진 유형일 것이므로 그런 문제가 발생할 것입니다. 유사하게 WPF에서 Window Forms으로 만든 컨트롤을 가져와 사용할 때도 마찬가지의 문제가 발생하는 것입니다. Button이나 DataGrid를 얹고 싶다면 그것들도 역시 XamlHost로 엮어서 Window 위에 얹어지도록 해야 합니다.
정성태
2019-04-30 07시57분
[Taylor] Thank you! I just spent a day trying to understand why I couldn't get the XAML Hosting to work -- you're the only person on the internet who explained it was because I wasn't on Windows 1809
[guest]

... 121  122  123  124  125  126  127  128  129  [130]  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1806정성태11/10/201425131.NET Framework: 477. SeCreateGlobalPrivilege 특권과 WCF NamedPipe
1805정성태11/5/201421964.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [3]파일 다운로드1
1804정성태11/5/201428193.NET Framework: 475. ETW(Event Tracing for Windows)를 C#에서 사용하는 방법 [9]파일 다운로드1
1803정성태11/4/201420299오류 유형: 261. Windows Server Backup 오류 - Error in backup of E:\$Extend\$RmMetadata\$TxfLog
1802정성태11/4/201422236오류 유형: 260. 이벤트 로그 - Windows Error Reporting / AEAPPINVW8
1801정성태11/4/201427581오류 유형: 259. 이벤트 로그 - Windows Error Reporting / IPX Assertion / KorIME.exe [1]
1800정성태11/4/201418242오류 유형: 258. 이벤트 로그 - Starting a SMART disk polling operation in Automatic mode.
1799정성태11/4/201423063오류 유형: 257. 이벤트 로그 - The WMI Performance Adapter service entered the stopped state.
1798정성태11/4/201431842오류 유형: 256. 이벤트 로그 - The WinHTTP Web Proxy Auto-Discovery Service service entered the stopped state. [1]
1797정성태11/4/201417519오류 유형: 255. 이벤트 로그 - The Adobe Flash Player Update Service service entered the stopped state.
1796정성태10/30/201424519개발 환경 구성: 249. Visual Studio 2013에서 Mono 컴파일하는 방법
1795정성태10/29/201427024개발 환경 구성: 248. Lync 2013 서버 설치 방법
1794정성태10/29/201422496개발 환경 구성: 247. "Microsoft Office 365 Enterprise E3" 서비스에 대한 간략 소개
1793정성태10/27/201423118.NET Framework: 474. C# - chromiumembedded 사용 - 두 번째 이야기 [2]파일 다운로드1
1792정성태10/27/201423279.NET Framework: 473. WebClient 객체에 쿠키(Cookie)를 사용하는 방법
1791정성태10/22/201423000VC++: 83. G++ - 템플릿 클래스의 iterator 코드 사용에서 발생하는 컴파일 오류 [5]
1790정성태10/22/201418533오류 유형: 254. NETLOGON Service is paused on [... AD Server...]
1789정성태10/22/201421199오류 유형: 253. 이벤트 로그 - The client-side extension could not remove user policy settings for '...'
1788정성태10/22/201423230VC++: 82. COM 프로그래밍에서 HRESULT 타입의 S_FALSE는 실패일까요? 성공일까요? [2]
1787정성태10/22/201431399오류 유형: 252. COM 개체 등록시 0x8002801C 오류가 발생한다면?
1786정성태10/22/201432693디버깅 기술: 65. 프로세스 비정상 종료 시 "Debug Diagnostic Tool"를 이용해 덤프를 남기는 방법 [3]파일 다운로드1
1785정성태10/22/201421938오류 유형: 251. 이벤트 로그 - Load control template file /_controltemplates/TaxonomyPicker.ascx failed [1]
1784정성태10/22/201430025.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법파일 다운로드1
1783정성태10/21/201423457VC++: 81. 프로그래밍에서 borrowing의 개념
1782정성태10/21/201420200오류 유형: 250. 이벤트 로그 - Application Server job failed for service instance Microsoft.Office.Server.Search.Administration.SearchServiceInstance
1781정성태10/21/201420624디버깅 기술: 64. new/delete의 짝이 맞는 경우에도 메모리 누수가 발생한다면?
... 121  122  123  124  125  126  127  128  129  [130]  131  132  133  134  135  ...