【问题标题】:WPF MVVM Grid With Button Column带有按钮列的 WPF MVVM 网格
【发布时间】:2018-08-31 11:02:02
【问题描述】:

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

<Button  Command="{Binding Path=ParentRow.DataContext, 
         RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
         UpdateSourceTrigger=PropertyChanged, Mode=Default}" 
         lib:Event.Binding="Click.[**NameOfViewModelMethod**]" >                                      
</Button>  

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    首先,如果您的Button 位于具有已定义DataContextGrid 内,则您无需像Path=ParentRow.DataContext 那样设置Path

    您的Command 绑定应该是这样的:

    <Button Command="{Binding YourVMICommand"} /> 
    

    你必须在你的虚拟机中定义一个public ICommand,然后将它绑定到按钮上。

    【讨论】:

      【解决方案2】:

      您不会显示所有代码和上下文,但它应该像这样工作 我假设您在用户控件中调用父数据上下文... (以列表视图为例):

      <ListView   ItemsSource="{Binding listFromDataContext, IsAsync=True}" Margin="3,51,0,10"    >
      
      <ListView.ItemTemplate >
      <DataTemplate>
      <grid>
       <Button   Command="{Binding DataContext.MyMethode, RelativeSource={RelativeSource AncestorType={x:Type controls:thisUserControl}}}" CommandParameter="{Binding}"   />
      </grid>
      </DataTemplate>
        </ListView.ItemTemplate >
      </ListView>
      

      然后在模型中

            private ICommand _MyMethode;
                  public ICommand MyMethode
                  {
                      get
                      {
                          return _MyMethode ?? (_MyMethode = new CommandHandler<MyModel.item>(x => showMessage(x), _canExecute));
                      }
                  }
      
      public void showMessage(MyModel.item x)
      {
      MessageBox.Show(x.Info);
      }
      

      【讨论】:

      • 你好 Zwan.. 谢谢你的回复......如果你能提供更多的代码,那就太好了。
      猜你喜欢
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 2011-06-22
      • 2018-01-15
      相关资源
      最近更新 更多