【问题标题】:How to build my own close button?如何建立自己的关闭按钮?
【发布时间】:2016-09-12 06:39:54
【问题描述】:

我有一个带有 MVVM 的 wpf 应用程序。我正在尝试在这里构建自己的关闭按钮。基于这个答案Creating a custom Close Button in WPF 我在 View(xaml.cs) 代码中添加了一个按钮事件处理程序。但是,它无法识别 Close(); 调用(上下文中不存在 - 无法解析符号)。

我还尝试了其他答案并将Command 和CommandParameter 添加到我的按钮的xaml 中。但背后的功能并没有得到点击。在How to bind Close command to a button 中使用RelayCommand 我的wpf 也无法识别RelayCommand。然后How can I use the RelayCommand in wpf 说我必须自己写(真的吗?)。我记得有一种简单的方法,类似于为按钮设置一个事件处理程序并调用Close();。但是,我该怎么做,或者为什么它对我不起作用?

查看代码:

private void closeButton_Click(object sender, RoutedEventArgs e)
{
    // I want to call close the whole app on button click
    //Close(); is not recognized
}

private void performMainCloseButtonCommand(object Parameter)
{
    // This doesn't get hits on button click
    Window objWindow = Parameter as Window;
    objWindow.Close();
}

按钮 XAML:

        <Button x:Name="closeButton" RenderTransformOrigin="0.5,0.5" Padding="0" Margin="701,0,0,0" BorderThickness="0" Click="closeButton_Click" Command="{Binding MainCloseButtonCommand}" CommandParameter="{Binding ElementName = mainWindow}" Height="45" Width="45" >
            <StackPanel Height="45" Width="45">
                <Image x:Name="closeButtonImage" Margin="0" Source="/ProjectName;component/Resources/x.fw.png" Height="33"/>
                <TextBlock Text="Close" Width="36" Padding="6,0,0,0" HorizontalAlignment="Center" Height="13" FontSize="10"/>
            </StackPanel>
        </Button>

【问题讨论】:

  • 如果您只在视图和后面的代码中工作,您可能没有准确地遵循 MVVM 模式。在大多数情况下,RelayCommands 用于代替点击事件。

标签: c# wpf xaml mvvm


【解决方案1】:

在您的事件处理程序中无法识别 Close,因为您当前的类中可能没有称为 Close 的方法。如果你想调用主窗口的关闭方法,你可以使用:

private void closeButton_Click(object sender, RoutedEventArgs e)
{
 Application.Current.MainWindow.Close();    
}

Above 不是一个好方法,并且不符合 MVVM 模式。这与你的第二个问题有关。如果没有看到代码的剩余部分,很难说为什么命令绑定不起作用。我猜您没有正确连接命令以使其触发。您需要确保已创建 RelayCommand 实例并且正确设置了命令属性。

【讨论】:

  • 我不同意与 MVVM 对齐的部分。我的观点是,如果逻辑只与视图有关,那么包含在代码隐藏中就可以了。因此,假设在启动关闭操作时不需要保存逻辑或返回逻辑(业务逻辑),那么仍然可以通过将关闭逻辑放在代码隐藏中来遵守关注点分离。
猜你喜欢
  • 2013-12-30
  • 2012-09-12
  • 2011-02-04
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
  • 2013-01-13
  • 2015-01-23
相关资源
最近更新 更多