猿问

带有按钮列的 WPF MVVM 网格

我正在遵循 MVVM 模式。我有一个包含几列的网格,其中一列包含 Button。单击按钮我想打开对话框,该对话框将显示与单击按钮的特定行相关的数据。但问题在于绑定,因为我无法将控件与视图模型绑定。


<Button  Command="{Binding Path=ParentRow.DataContext, 

         RelativeSource={RelativeSource AncestorType={x:Type UserControl}},

         UpdateSourceTrigger=PropertyChanged, Mode=Default}" 

         lib:Event.Binding="Click.[**NameOfViewModelMethod**]" >                                      

</Button>  


回首忆惘然
浏览 164回答 2
2回答

一只斗牛犬

你没有显示你所有的代码和上下文,但它应该像这样工作我假设你在一个用户控件中校准父数据上下文......(以列表视图为例):<ListView&nbsp; &nbsp;ItemsSource="{Binding listFromDataContext, IsAsync=True}" Margin="3,51,0,10"&nbsp; &nbsp; ><ListView.ItemTemplate ><DataTemplate><grid>&nbsp;<Button&nbsp; &nbsp;Command="{Binding DataContext.MyMethode, RelativeSource={RelativeSource AncestorType={x:Type controls:thisUserControl}}}" CommandParameter="{Binding}"&nbsp; &nbsp;/></grid></DataTemplate>&nbsp; </ListView.ItemTemplate ></ListView>然后在模型中&nbsp; &nbsp; &nbsp; private ICommand _MyMethode;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public ICommand MyMethode&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return _MyMethode ?? (_MyMethode = new CommandHandler<MyModel.item>(x => showMessage(x), _canExecute));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }public void showMessage(MyModel.item x){MessageBox.Show(x.Info);}

眼眸繁星

首先,如果您Button在 a 中Grid,DataContext则不需要设置Pathlike&nbsp;Path=ParentRow.DataContext。你的Command绑定应该是这样的:<Button&nbsp;Command="{Binding&nbsp;YourVMICommand"}&nbsp;/>您必须public ICommand在 VM 中定义一个,然后将其绑定到按钮。
随时随地看视频慕课网APP
我要回答