[WPF]는 View의 인스턴스를 ReactiveProperty를 사용하여 ViewModel에 전달합니다.

4541 단어 ReactivePropertyC#WPF
※ 이 기사가 쓴 방법은 MVM의 원칙을 훼손할 수 있으므로 추천하지 않습니다.이를 이해한 토대 위에서 강행하려는 이들을 겨냥한 기사다.
최근에는 WPF를 쓰기 시작했다. MVM에 코드를 쓸 때 View 모델의View 실례를 원한다는 생각이 자주 들기 때문에 얻은 방법을 잊어버리고 녹음하는 것으로 삼았다.
개인적으로 C#+WPF에 MVM 코드를 쓰지 않으려면 ReactiveProperty가 없습니다.
환경NET FrameWork4.8,Visual Studio Community 2019
(.NET Core도 NET5도 Visual Studio 2017 Express도 움직인다)

차리다


먼저 뷰를 전제 조건으로 설정합니다.Xaml의 DataContext에서 ViewModel을 참조합니다.
Prism 등의 MVM 프레임워크를 사용하면 자동으로 등록되며, 그렇지 않으면 Window와 User Control에서 이러한 느낌으로 지정됩니다.
MainWindow.xaml
  <Window.DataContext>
     <local:MainWindowViewModel/>
  </Window.DataContext>
① 프로젝트 → Nugget 패키지의 관리에 따라 ReactiveProperty.WPF를 추가합니다.

②View.xaml에 다음 인용을 추가합니다.
MainWindow.xaml
xmlns:bh="http://schemas.microsoft.com/xaml/behaviors"
xmlns:rp="clr-namespace:Reactive.Bindings.Interactivity;assembly=ReactiveProperty.WPF"
③ViewModel.cs에 다음 인용을 추가합니다.
MainWindowViewModel.cs
using System.Windows;
using Reactive.Bindings;

획득 방법


View.xaml에서 Event ToReactiveCommand를 사용하여 Loaded 이벤트를 명령으로 변환한 후 ViewModel에 전달합니다.
MainWindow.xaml
<!--参照の定義の下、ボタンなどの要素の上に書きます。-->
  <bh:Interaction.Triggers>
      <bh:EventTrigger EventName="Loaded">
          <rp:EventToReactiveCommand Command="{Binding LoadCommand}" />
      </bh:EventTrigger>
  </bh:Interaction.Triggers>
받은 명령의 Routed EventArgs 입니다.Source에서 Window 인스턴스를 가져옵니다.
다른 곳에서 사용할 수 있도록 적당한 변수에 먼저 넣을 수 있다.
MainWindowViewModel.cs
    public class MainWindowViewModel{

        public ReactiveCommand<RoutedEventArgs> LoadCommand { get; }
        private MainWindow _mainWindow; 

        public MainWindowViewModel() {

            //必要に応じて.addToやClassTerminateなどでオブジェクトの解放を定義しておきます。 
            LoadCommand =
                new ReactiveCommand<RoutedEventArgs>()
                    .WithSubscribe(e => _mainWindow = (MainWindow)e.Source);

           //例えばこんな感じのコマンドを作ってウィンドウを閉じることが出来ます。
           //このコードはメンバ定義もバインディングもしてないのでこのままでは動きません。
           hogehogeCommand=
               new ReactiveCommand()
                   .WithSubscribe(() => _mainWindow.Close());

        }
    }

감상


Window와 Window에서 읽은 User Control 자체의 상태는 어디에서 관리되는지 잘 모르겠어요.
(불러낸 윈도의 View Model은 책임이 있는지, DI에 등록된 Model과 연결하는 것이 좋은지...등)

좋은 웹페이지 즐겨찾기