如何在代码隐藏中绑定命令以在WPF中查看?

时间:2016-10-18 14:17:49

标签: c# wpf xaml

我想从我视图中的按钮(GenericReportingView.xaml)中的代码隐藏(GenericReportingView.xaml.cs)中执行命令..

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

但命令没有被调用.. 任何帮助将不胜感激。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您不应该绑定到代码隐藏中的属性。绑定通常用于将控件链接到视图模型中的属性(在这种情况下,它看起来不像您有视图模型)。相反,您可以使用按钮上的单击处理程序来调用您的方法:

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