WPF MVVM Button Control Binding in DataTemplate

前端 未结 3 1717
难免孤独
难免孤独 2021-01-14 09:34

I\'ve seen other questions that deal with this, but never any explicit code describing the fix. I can\'t get a button inside of my ItemTemplate to bind to ANY command anywhe

相关标签:
3条回答
  • 2021-01-14 09:58

    The button in the datatemplate should bind to command PauseCommand since it's datacontext is PrinterViewModel and not MainWindowViewModel. If you look in the debug output VS will clearly tell you that.

    0 讨论(0)
  • 2021-01-14 10:01

    The DataContext for the Button inside your ItemTemplate is a PrinterViewModel object (which has the PauseCommand). However, you're trying to bind the PausePrinterCommand to it, which is a property of the MainWindowViewModel.

    In order to make this work (i.e. execute the MainViewModel.PausePrinterCommand using a Button in your ItemTemplate), you'll have to somehow get the MainViewModel first.

    One way to do this is to use a RelativeSource for your binding, find the Window, and use DataContext.PausePrinterCommand as the Binding path. Like this:

    <Button Grid.Column="1" Content="Pause"
            Command="{Binding RelativeSource={RelativeSource Window},
                      Path=DataContext.PausePrinterCommand}" />
    
    0 讨论(0)
  • 2021-01-14 10:01

    use element binding

    <Window x:Class="RET.CMS.Printing.App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:RET.CMS.Printing.App.ViewModel"
        Height="350" Width="525"
        x:Name="rootWindow"
        WindowStartupLocation="CenterScreen"
        Title="{Binding Path=DisplayName}" >
           .
           .
           .
      <Button Grid.Column="1" Content="Pause" Command="{Binding ElementName=rootWindow, Path=DataContext.PausePrinterCommand}"></Button>
    
    0 讨论(0)
提交回复
热议问题