1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【WPF】ViewModelからユーザーコントロールのオブジェクトを取得する

Posted at

ViewModelからユーザーコントロールのオブジェクトを取得する際に
やり方がわからず躓いたのでメモ。
※ReactivePropertyを使用しています。
http://blog.okazuki.jp/entry/2015/02/22/212827

アプリの構成は以下の通り。
・MainWindow
・SubControl
・Sub2Control
MainWindowはSubControlを呼び、SubControlはSub2Controlを呼んでいる。

今回は、SubControlのButtonが押下された時にイベントをSubControlViewModelで受け取り、
Sub2Contorlのオブジェクトを取得したい。

SubControl.xaml
<Grid>
 <Button Header="Get Sub2Heith" Command="xxx"/>
 <local:Sub2Control x:Name="Sub2Control"/>
</Grid>
SubControlViewModel.cs
xxx.Subscribe(x =>
{
     var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w is MainWindow);
     var mw = (MainWindow)window;
     var stackPanelsHeight = mw.SubControl.Sub2Control.ActualHeight;
}

SubControlViewModel.csの説明

Applicationクラス

Windows Presentation Foundation (WPF) アプリケーションをカプセル化します。
名前空間: System.Windows
アセンブリ: PresentationFramework (PresentationFramework.dll 内)

Application.Current
→ApplicationのCurrentプロパティはstaticなので、Applicationのオブジェクトを作成する必要がない。

Application.Current.Windows
→現在のAppDomainのApplicationオブジェクトから、インスタンス化されたWindowを取得

ウィンドウがuser interface (UI) スレッド上でインスタンス化されると、直ちに Window 参照が Windows に自動的に追加されます。ワーカー スレッドによって作成されたウィンドウは追加されません。 Window 参照は、Closing イベントが処理されてから Closed イベントが発生するまでの間に、自動的に削除されます。
既定では、Windows プロパティに追加された最初の項目が MainWindow となります。
このプロパティは、Application オブジェクトを作成したスレッドからのみ使用できます。

スレッドについては下記参照
http://article.higlabo.com/ja/thread_fundamentals.html

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?