简体   繁体   中英

How to bind command in code-behind to view in WPF?

I want to execute a command in my code-behind (GenericReportingView.xaml.cs) from a button in my view (GenericReportingView.xaml)..

GenericReportingView.xaml:

 <Grid  Grid.Row="0" Grid.Column="0">
     <Button Content="GetReport" Command="{Binding GetReportCommand}" HorizontalAlignment="Left" Width="50" />
 </Grid>

GenericReportingView.xaml.cs:

public partial class GenericReportingView
{
    private DelegateCommand _getReportCommand;
    public DelegateCommand GetReportCommand
    {
        get { return _getReportCommand ?? (_getReportCommand = new DelegateCommand(GetReport, (obj) => true)); }
    }

    public GenericReportingView()
    {
        InitializeComponent();
    }

    public void GetReport(object obj)
    {
        //Do something..
    }
}

But the command isn't getting called.. Any help will be much appreciated.

Thanks in advance.

You shouldn't be binding to properties in your code-behind. Bindings are usually used to link controls to properties in your view model (and it doesn't look like you have a view model in this case). Instead you could just use the click handler on the button to call your method:

GenericReportView.xaml:

<Grid  Grid.Row="0" Grid.Column="0">
    <Button Content="GetReport" Click="GetReport" HorizontalAlignment="Left" Width="50" />
</Grid>

GenericReportView.xaml.cs

public partial class GenericReportingView
{
    public GenericReportingView()
    {
        InitializeComponent();
    }

    public void GetReport(object obj, RoutedEventArgs e)
    {
        //Do something..
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM