【发布时间】: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用于代替点击事件。