R.Tanaka.Ichiro's Blog

主にC# な話題です

目次

Blog 利用状況

ニュース

WPF の Document と View

ここ数日

WPF の Document と View

の問題で少し悩んでいました。

で、こんな感じで書くとキャストのコストが軽減されて、View に対する Document の差し替えも容易なのかなと思ったのでメモしておこうかと思います。
ちなみに、動作テストしてないで、ただ書きなぐっただけなので、動く保証はないです。


[XAML]
<Window x:Class="Hoge.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:Hoge">
  <Grid>
    <TextBox Text="{Binding Path=Code}" />
  </Grid>
</Window>


[View]
public partial class MainWindow : Window
{
  private Document document = null;

  public MainPage() {
    this.InitializeComponent();
    this.DataContextChanged += (s, e) => {
      this.document = this.DataContext as Document;
      if (this.document == null) throw new InvalidCastException();
    };
  }
}


[Document]
public class Document : INotifyPropertyChanged
{
  protected virtual void OnPropertyChanged(string propertyName) {
    if (this.PropertyChanged == null) return;
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }

  private int _Code;
  public int Code {
    get { return this._Code; }
    set {
      if (this._Code == value) return;
      this._Code = value;
      this.OnPropertyChanged("Code");
    }
  }
}


[Main]
var d = new Document();
var v = new View();
v.DataContext = d;
v.Show();


View 内部で Document オブジェクトを生成してしまうと、View オブジェクトの DataContext メンバによる差し替えができなくなってしまうので、上記のようにしておくと便利です。多分。

投稿日時 : 2009年6月23日 13:42

Feedback

# re: WPF の Document と View 2009/06/23 16:02 えムナウ

M-V-VMパターンに近いですね。

# re: WPF の Document と View 2009/06/24 11:13 とっちゃん

MVVMに近いというか、お作法取っ払ったらこうなる(正確に言うと、もともとWPFのデータコンテキストの仕組みがコントローラw)だけかと。。。

ModelとViewModel(DataContextに貼り付けるオブジェクト)をお作法に合わせてやれば
ほぼそのまま、MVVMパターンになると思いますよ。

# re: WPF の Document と View 2009/06/24 14:49 R・田中一郎

まー、結局はそういうことですね。
今回、いろいろ考えて、やっぱり MVVMパターンが一番いいやという感じですか。

# re: WPF の Document と View 2009/06/24 15:45 とっちゃん

MVVMが一番かどうかは、ほかのものを知らないので何とも。。。

でも、最終的には、フレームワークとしてというより、IDE側のフォローがないと浸透は難しいんじゃない?

という気がしますね。

# re: WPF の Document と View 2009/06/25 11:23 R・田中一郎

一番いいや、というのは僕の感想です。

>でも、最終的には、フレームワークとしてというより、IDE側のフォローがないと浸透は難しいんじゃない?

IDE 側のフォローがないとコーディングすらできな体になっている僕にとっては、あまり重要な問題ではありませんw

# WPF の Document と View(その2) 2009/06/26 14:03 R.Tanaka.Ichiro's Blog

WPF の Document と View(その2)

# WPF の Document と View(その2) 2009/06/26 14:06 R.Tanaka.Ichiro's Blog

WPF の Document と View(その2)

タイトル
名前
Url
コメント