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]

... 61  62  63  64  [65]  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12017정성태9/11/201911877오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201912834오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201916720개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201911185개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201913972개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201917850.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
12011정성태8/27/201915956사물인터넷: 57. C# - Rapsberry Pi Zero W와 PC 간 Bluetooth 통신 예제 코드파일 다운로드1
12010정성태8/27/201911342VS.NET IDE: 138. VSIX - DTE.ItemOperations.NewFile 메서드에서 템플릿 이름을 다국어로 설정하는 방법
12009정성태8/26/201911916.NET Framework: 858. C#/Windows - Clipboard(Ctrl+C, Ctrl+V)가 동작하지 않는다면?파일 다운로드1
12008정성태8/26/201911660.NET Framework: 857. UWP 앱에서 SQL Server 데이터베이스 연결 방법
12007정성태8/24/201910843.NET Framework: 856. .NET Framework 버전을 올렸을 때 오류가 발생할 수 있는 상황
12006정성태8/23/201914062디버깅 기술: 129. guidgen - Encountered an improper argument. 오류 해결 방법 (및 windbg 분석) [1]
12005정성태8/13/201912014.NET Framework: 855. 닷넷 (및 VM 계열 언어) 코드의 성능 측정 시 주의할 점 [2]파일 다운로드1
12004정성태8/12/201919786.NET Framework: 854. C# - 32feet.NET을 이용한 PC 간 Bluetooth 통신 예제 코드 [14]
12003정성태8/12/201912508오류 유형: 564. Visual C++ 컴파일 오류 - fatal error C1090: PDB API call failed, error code '3'
12002정성태8/12/201911498.NET Framework: 853. Excel Sheet를 WinForm에서 사용하는 방법 - 두 번째 이야기 [5]
12001정성태8/10/201916006.NET Framework: 852. WPF/WinForm에서 UWP의 기능을 이용해 Bluetooth 기기와 Pairing하는 방법 [1]
12000정성태8/9/201914897.NET Framework: 851. WinForm/WPF에서 Console 창을 띄워 출력하는 방법파일 다운로드1
11999정성태8/1/201910652오류 유형: 563. C# - .NET Core 2.0 이하의 Unix Domain Socket 사용 시 System.IndexOutOfRangeException 오류
11998정성태7/30/201911833오류 유형: 562. .NET Remoting에서 서비스 호출 시 SYN_SENT로 남는 현상파일 다운로드1
11997정성태7/30/201913378.NET Framework: 850. C# - Excel(을 비롯해 Office 제품군) COM 객체를 제어 후 Excel.exe 프로세스가 남아 있는 문제 [2]파일 다운로드1
11996정성태7/25/201915804.NET Framework: 849. C# - Socket의 TIME_WAIT 상태를 없애는 방법파일 다운로드1
11995정성태7/23/201918908.NET Framework: 848. C# - smtp.daum.net 서비스(Implicit SSL)를 이용해 메일 보내는 방법 [2]
11994정성태7/22/201914412개발 환경 구성: 454. Azure 가상 머신(VM)에서 SMTP 메일 전송하는 방법파일 다운로드1
11993정성태7/22/20199874오류 유형: 561. Dism.exe 수행 시 "Error: 2 - The system cannot find the file specified." 오류 발생
11992정성태7/22/201911635오류 유형: 560. 서비스 관리자 실행 시 "Windows was unable to open service control manager database on [...]. Error 5: Access is denied." 오류 발생
... 61  62  63  64  [65]  66  67  68  69  70  71  72  73  74  75  ...