全て
| カテゴリ未分類
| 通常
| 数学
| 投資
| 副業
| 転職・就職
| ブログ
| 株Stock
| VBA
| SharePoint
| REST API
| RenderListDataAsStream
| PowerAutomateDesktop
| Graph API
| PowerApps
| PowerAutomate
| PowerFx
| OfficeScriptオフィススクリプト
| PowerAutomate日時Excel日時相互関係
| PowerShell
| Dataverse
| UiPath
| OneDrive
| LINQ
| VB.NET
| C#.NET
| WPFC#.NET
| Git
カテゴリ:C#.NET
MVVM (Model-View-ViewModel) パターンを使用した C# WPF のサンプルコードを以下に示します。 まず、ViewModel を定義します。 ```csharp using System.ComponentModel; namespace YourNamespace { public class MainViewModel : INotifyPropertyChanged { private string _displayText; public string DisplayText { get { return _displayText; } set { if (_displayText != value) { _displayText = value; OnPropertyChanged("DisplayText"); } } } public MainViewModel() { DisplayText = "Hello, MVVM!"; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ``` 次に、View を作成します。 ```xml <Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MVVM Sample" Height="200" Width="300" DataContext="{Binding MainViewModel, Source={StaticResource Locator}}"> <Grid> <TextBlock Text="{Binding DisplayText}" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Grid> </Window> ``` 最後に、ViewModel をローカライズします。 ```csharp using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight; namespace YourNamespace { public class ViewModelLocator { static ViewModelLocator() { SimpleIoc.Default.Register<MainViewModel>(); } public MainViewModel MainViewModel { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } } } ``` これは、非常に基本的な MVVM のサンプルです。ViewModel がビューにデータを提供し、ビューが ViewModel によって変更を通知するように構成されています。ビューモデルのインスタンスは、ViewModelLocator を使用してビューに注入されます。 お気に入りの記事を「いいね!」で応援しよう
Last updated
2024.04.20 14:14:01
[C#.NET] カテゴリの最新記事
|