こんにちは。
プロジェクトはModel、View、ViewModelの3つで構成されており、ViewModelがModelのインスタンスを保持してViewに公開しています。
その上で質問です。
View:
XAML
1<Window x:Class="TestWpf.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:TestWpf" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="350" Width="525"> 9 <Window.DataContext> 10 <local:ViewModel/> 11 </Window.DataContext> 12 <Grid DataContext="{Binding M}"> 13 <Grid.ColumnDefinitions> 14 <ColumnDefinition Width="0.5*"></ColumnDefinition> 15 <ColumnDefinition Width="0.5*"></ColumnDefinition> 16 </Grid.ColumnDefinitions> 17 <Grid.RowDefinitions> 18 <RowDefinition Height="0.5*"></RowDefinition> 19 <RowDefinition Height="0.5*"></RowDefinition> 20 </Grid.RowDefinitions> 21 <Grid Row="0" Column="0"> 22 <TextBlock Text="{Binding Name}"></TextBlock> 23 </Grid> 24 <Grid Row ="0" Column="1"> 25 <TextBlock Text="{Binding Name}"></TextBlock> 26 </Grid> 27 <Grid Row="1" Column="0"> 28 <TextBlock Text="{Binding Name}"></TextBlock> 29 </Grid> 30 <Grid Row="1" Column="1"> 31 <!-- コマンドを追加したい --> 32 </Grid> 33 </Grid> 34</Window>
ViewModel:
C#
1 class ViewModel:INotifyPropertyChanged { 2 public event PropertyChangedEventHandler PropertyChanged; 3 4 private ICommand Command { 5 get; 6 set; 7 } 8 private Model _m; 9 10 public Model M { 11 get { 12 return this._m; 13 } 14 set { 15 this._m = value; 16 OnPropertyChanged("M"); 17 } 18 } 19 20 public ViewModel() { 21 this.M = new Model(); 22 this.M.Name = "nana"; 23 this.Command = new RoutedUICommand(); 24 } 25 26 27 private void OnPropertyChanged( string name ) { 28 var handler = this.PropertyChanged; 29 handler?.Invoke( this, new PropertyChangedEventArgs( name ) ); 30 } 31 }
Model:
C#
1 class Model :INotifyPropertyChanged { 2 public event PropertyChangedEventHandler PropertyChanged; 3 4 private string _name; 5 6 public string Name { 7 get { 8 return this._name; 9 } 10 set { 11 this._name = value; 12 OnPropertyChanged("Name"); 13 } 14 } 15 16 17 private void OnPropertyChanged( string name ) { 18 var handler = this.PropertyChanged; 19 handler?.Invoke( this, new PropertyChangedEventArgs( name ) ); 20 } 21 }
Viewは上記のような田の字に区画がわかれており、それを包括するGridでデータコンテキストにModelのインスタンスを設定しています。
そのうち田の字の一区画に
XAML
1<Button Content="改名" Command="{Binding Command}"></Button>
のようなボタンを設置し、コマンドをBindingしたいと考えています。
ここで問題になるのが、12行目のDataContextの設定です。
XAML
1<Grid DataContext="{Binding M}">
これのおかげでViewModel直下のプロパティであるCommandをBindingすることが出来ません。
この場合、それぞれの田の字の区画を構成するGrid一つ一つのDataContextにModelをBindingするべきなのでしょか。
出来ることなら他の全てのコントロールのBindingはModel下のプロパティに対するものなので、外側のGridでDataContext={Binding M}をしてしまい、ボタンのBindingのみ例外というような記述にしたいのですが、それは可能なのでしょうか。
それとも、MVVMやBindingの考え方から間違っているのでしょうか。
御指南御指摘よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/01 21:58