참고 항목
이 문서의 최신 버전은 아닙니다. 현재 릴리스는 이 문서의 .NET 9 버전을 참조 하세요.
Important
이 정보는 상업적으로 출시되기 전에 실질적으로 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적, 또는 묵시적인 보증을 하지 않습니다.
현재 릴리스는 이 문서의 .NET 9 버전을 참조 하세요.
이 문서에서는 앱에서 루트 구성 요소 매개 변수를 Blazor Hybrid 전달하는 방법을 설명합니다.
클래스 BlazorWebView
는 RootComponent
루트 구성 요소에 Parameters
전달할 매개 변수의 선택적 사전을 나타내는 형식IDictionary<string, object?>?
의 속성을 정의합니다.
- .NET MAUI: Microsoft.AspNetCore.Components.WebView.Maui.RootComponent
- WPF: Microsoft.AspNetCore.Components.WebView.Wpf.RootComponent
- Windows Forms: Microsoft.AspNetCore.Components.WebView.WindowsForms.RootComponent
다음 예제에서는 뷰 모델을 루트 구성 요소에 전달하여 뷰 모델을 앱 부분의 구성 요소에 Blazor 연계 형식 Razor 으로 추가로 전달합니다. 이 예제는 설명서의 키패드 예제를 기반으로 합니다 .NET MAUI .
- 데이터 바인딩 및 MVVM: 명령(.NET MAUI 설명서): 키패드 예제를 사용하여 MVVM으로 데이터 바인딩을 설명합니다.
- .NET MAUI 샘플
키패드 예제에서는 앱에서 MVVM 패턴을 구현하는 데 중점을 두고 있습니다 .NET MAUIBlazor Hybrid .
- 루트 구성 요소에 전달된 개체 사전은 앱의 구성 요소에서 사용하기 위해 하나 이상의 매개 변수를 루트 구성 요소에 Razor 전달해야 하는 모든 용도의 모든 형식을 포함할 수 있습니다.
- 다음 .NET MAUIBlazor 예제에서 보여 준 개념은 Windows Forms Blazor 앱 및 WPF Blazor 앱과 동일합니다.
앱에 다음 보기 모델을 배치합니다 .NET MAUIBlazor Hybrid .
KeypadViewModel.cs
:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace MauiBlazor;
public class KeypadViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _inputString = "";
private string _displayText = "";
private char[] _specialChars = { '*', '#' };
public ICommand AddCharCommand { get; private set; }
public ICommand DeleteCharCommand { get; private set; }
public string InputString
{
get => _inputString;
private set
{
if (_inputString != value)
{
_inputString = value;
OnPropertyChanged();
DisplayText = FormatText(_inputString);
// Perhaps the delete button must be enabled/disabled.
((Command)DeleteCharCommand).ChangeCanExecute();
}
}
}
public string DisplayText
{
get => _displayText;
set
{
if (_displayText != value)
{
_displayText = value;
OnPropertyChanged();
}
}
}
public KeypadViewModel()
{
// Command to add the key to the input string
AddCharCommand = new Command<string>((key) => InputString += key);
// Command to delete a character from the input string when allowed
DeleteCharCommand =
new Command(
// Command strips a character from the input string
() => InputString = InputString.Substring(0, InputString.Length - 1),
// CanExecute is processed here to return true when there's something to delete
() => InputString.Length > 0
);
}
string FormatText(string str)
{
bool hasNonNumbers = str.IndexOfAny(_specialChars) != -1;
string formatted = str;
// Format the string based on the type of data and the length
if (hasNonNumbers || str.Length < 4 || str.Length > 10)
{
// Special characters exist, or the string is too small or large for special formatting
// Do nothing
}
else if (str.Length < 8)
formatted = string.Format("{0}-{1}", str.Substring(0, 3), str.Substring(3));
else
formatted = string.Format("({0}) {1}-{2}", str.Substring(0, 3), str.Substring(3, 3), str.Substring(6));
return formatted;
}
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
이 문서의 예제에서 앱의 루트 네임스페이스는 MauiBlazor
. 앱의 KeypadViewModel
루트 네임스페이스에 맞게 네임스페이스를 변경합니다.
namespace MauiBlazor;
참고 항목
샘플 앱 및 .NET MAUI 설명서에 대한 .NET MAUI 보기 모델을 만들 때 KeypadViewModel
보기 모델은 이름이 지정된 ViewModels
폴더에 배치되었지만 네임스페이스는 앱의 루트로 설정되었으며 폴더 이름을 포함하지 않았습니다. 파일에 폴더 KeypadViewModel.cs
를 포함하도록 네임스페이스를 업데이트하려면 이 문서의 예제 코드를 일치하도록 수정합니다. 다음 파일에 (C#) 및 @using
() 문을 추가 using
하거나 보기 모델 형식{APP NAMESPACE}.ViewModels.KeypadViewModel
에 대한 참조를 완전히 정규화합니다. 여기서 {APP NAMESPACE}
자리 표시자는 앱의 루트 네임스페이스Razor입니다.
XAML에서 직접 설정할 Parameters
수 있지만 다음 예제에서는 XAML 파일의 루트 구성 요소(rootComponent
)의 이름을 지정하고 코드 숨김 파일에서 매개 변수 사전을 설정합니다.
MainPage.xaml
의 경우
<RootComponent x:Name="rootComponent"
Selector="#app"
ComponentType="{x:Type local:Main}" />
코드 숨김 파일(MainPage.xaml.cs
)에서 생성자에서 뷰 모델을 할당합니다.
public MainPage()
{
InitializeComponent();
rootComponent.Parameters =
new Dictionary<string, object>
{
{ "KeypadViewModel", new KeypadViewModel() }
};
}
다음 예제 에서는 앱 부분의 구성 요소 계층 Blazor 을 아래로 개체(KeypadViewModel
)를 다음과 같이 계단식으로 CascadingValue
배열합니다.
Main
구성 요소(Main.razor
)에서:
루트 구성 요소에 전달된 개체의 형식과 일치하는 매개 변수를 추가합니다.
@code { [Parameter] public KeypadViewModel KeypadViewModel { get; set; } }
구성 요소와
KeypadViewModel
함께 계단식으로 연결합니다CascadingValue
.<Found>
XAML 콘텐츠를 다음 태그로 업데이트합니다.<Found Context="routeData"> <CascadingValue Value="KeypadViewModel"> <RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" /> <FocusOnNavigate RouteData="routeData" Selector="h1"/> </CascadingValue> </Found>
이 시점에서 계단식 형식은 앱 전체의 구성 요소에서 Razor 로 CascadingParameter
사용할 수 있습니다.
다음 구성 요소 예제는 다음과 같습니다 Keypad
.
- 의 현재 값을
KeypadViewModel.DisplayText
표시합니다. - 표시 문자열 길이가 0보다 크면 명령을 호출
KeypadViewModel.DeleteCharCommand
하여 문자 삭제를 허용합니다 ICommand.CanExecute. - UI에서 누른 키를 사용하여 호출
KeypadViewModel.AddCharCommand
하여 문자 추가를 허용합니다.
Pages/Keypad.razor
:
@page "/keypad"
<h1>Keypad</h1>
<table id="keypad">
<thead>
<tr>
<th colspan="2">@KeypadViewModel.DisplayText</th>
<th><button @onclick="DeleteChar">⇦</button></th>
</tr>
</thead>
<tbody>
<tr>
<td><button @onclick="@(e => AddChar("1"))">1</button></td>
<td><button @onclick="@(e => AddChar("2"))">2</button></td>
<td><button @onclick="@(e => AddChar("3"))">3</button></td>
</tr>
<tr>
<td><button @onclick="@(e => AddChar("4"))">4</button></td>
<td><button @onclick="@(e => AddChar("5"))">5</button></td>
<td><button @onclick="@(e => AddChar("6"))">6</button></td>
</tr>
<tr>
<td><button @onclick="@(e => AddChar("7"))">7</button></td>
<td><button @onclick="@(e => AddChar("8"))">8</button></td>
<td><button @onclick="@(e => AddChar("9"))">9</button></td>
</tr>
<tr>
<td><button @onclick="@(e => AddChar("*"))">*</button></td>
<td><button @onclick="@(e => AddChar("0"))">0</button></td>
<td><button @onclick="@(e => AddChar("#"))">#</button></td>
</tr>
</tbody>
</table>
@code {
[CascadingParameter]
protected KeypadViewModel KeypadViewModel { get; set; }
private void DeleteChar()
{
if (KeypadViewModel.DeleteCharCommand.CanExecute(null))
{
KeypadViewModel.DeleteCharCommand.Execute(null);
}
}
private void AddChar(string key)
{
KeypadViewModel.AddCharCommand.Execute(key);
}
}
데모용으로만 다음 CSS 스타일을 파일의 콘텐츠에 wwwroot/index.html
배치하여 단추의 <head>
스타일을 지정합니다.
<style>
#keypad button {
border: 1px solid black;
border-radius:6px;
height: 35px;
width:80px;
}
</style>
다음 태그를 사용하여 구성 요소(Shared/NavMenu.razor
)에 NavMenu
사이드바 탐색 항목을 만듭니다.
<div class="nav-item px-3">
<NavLink class="nav-link" href="keypad">
<span class="oi oi-list-rich" aria-hidden="true"></span> Keypad
</NavLink>
</div>
추가 리소스
ASP.NET Core