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]

... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12927정성태1/18/20226679개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/20227181오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227272개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/20228756.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/20227671개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226734개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225713개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226466오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226314Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226562Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225771오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225495오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225779오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227706VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228225.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228868개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226193VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226664제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20228070오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225919.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226365오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226987.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226645오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228675개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227263.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227320오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...