c# - 如何在代码隐藏中绑定(bind)命令以在 WPF 中查看?

标签 c# wpf xaml

我想通过我 View (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>

通用报告 View .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..
    }
}

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

提前致谢。

最佳答案

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

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

关于c# - 如何在代码隐藏中绑定(bind)命令以在 WPF 中查看?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110705/

相关文章:

c# - WPF 在控件中添加自定义属性

c# - 无法加载文件或程序集 Microsoft.ReportViewer.ProcessingObjectModel,版本 = 13.0.0.0

wpf - 使用 WPF 在 F# 中调用窗口加载事件的方法

c# - WPF 绑定(bind)到父 DataContext

c# - Winforms Drawing.rectangle.union 的 WPF 等价物是什么?

c# - Xunit.Net 由于 ID 重复而跳过测试

wpf - 在 ItemsControl 中虚拟化高度为 * 的 ItemsControl

c# - 如何获得 Windows 10 强调色?

c# - Xamarin.Forms 动态布局取决于屏幕方向或大小

c# - C# 的 IVR 编程库