MVVM パターンに従って、Windows ストア アプリケーションがあります。GridView コントロールを含む親ビュー (一致する親 ViewModel を持つ) があります。その GridView コントロールの ItemTemplate には、子ビューが含まれています。その子ビューには、いくつかのボタンが含まれています。
ユーザーが ChildView コントロールの 1 つのボタンをクリックすると、親 ViewModel でメソッドが呼び出されるようにするにはどうすればよいですか?
MVVM パターンに従って、Windows ストア アプリケーションがあります。GridView コントロールを含む親ビュー (一致する親 ViewModel を持つ) があります。その GridView コントロールの ItemTemplate には、子ビューが含まれています。その子ビューには、いくつかのボタンが含まれています。
ユーザーが ChildView コントロールの 1 つのボタンをクリックすると、親 ViewModel でメソッドが呼び出されるようにするにはどうすればよいですか?
これには 2 つの方法があります。
これが私がこの問題を解決する方法でした。
子ビューのコード ビハインドに、ICommand でサポートされている依存関係プロパティを追加します。
public static readonly DependencyProperty ChildButtonCommandProperty = DependencyProperty.Register("ChildButtonCommand", typeof(ICommand), typeof(ChildView),new PropertyMetadata(null, OnChildButtonCommandChanged));
public ICommand ChildButtonCommand
{
get { return (ICommand)GetValue(ChildButtonCommandProperty); }
set { SetValue(ChildButtonCommandProperty, value); }
}
private static void OnChildButtonCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var self = (ChildView)sender;
self.ChildButtonCommand.Command = (ICommand)e.NewValue;
}
親 ViewModel で、 https ://relaycommandrt.codeplex.com/ にある RelayCommand で実装された ICommand 型のパブリック ゲッター プロパティを追加します。
親ビューの Xaml で、子ビューに ChildButtonCommand をバインドします。
<GridView.ItemTemplate>
<DataTemplate>
<views:ChildView ChildButtonCommand="{Binding ElementName=ParentView, Path=DataContext.PropertyOnParentViewModel}"/>
</DataTemplate>
バインディング構文を詳しく調べてください。GridView アイテムの DataTemplate にいるため、DataContext は親ビュー モデルではありません(子アイテム オブジェクトです)。ボタン コマンドを親ビュー モデルにバインドする場合は、親ビュー内の何かへの参照が必要です。この場合、ビューに「ParentView」という名前を付けました。Binding ElementName 構文を使用して、ParentView の DataContext、具体的には ParentViewModel のプロパティにバインドできます。