M Hilmi Koca M Hilmi Koca - 1 month ago 17
C# Question

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.

Answer

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..
    }
}