Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

xaml

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.

like image 979
M Hilmi Koca Avatar asked Apr 20 '26 15:04

M Hilmi Koca


1 Answers

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..
    }
}
like image 172
sam2929 Avatar answered Apr 22 '26 06:04

sam2929