ここ数日
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 メンバによる差し替えができなくなってしまうので、上記のようにしておくと便利です。多分。