Khalil Khalaf
Khalil Khalaf

Reputation: 9407

How to build my own close button?

I have a wpf application with a MVVM. I am trying here to build my own close button. Based on this answer Creating a custom Close Button in WPF I added a button event handler in the View(xaml.cs) code. However, it is not recognizing the Close(); call (doesn't exist in the context - Can't resolve symbol).

Also I tried the other answer and added Command and CommandParameter into my button's xaml. But the function behind is not getting hits. In How to bind Close command to a button using the RelayCommand also my wpf is not recognizing RelayCommand. Then How can I use the RelayCommand in wpf said that I have to write it myself(really?). I remember there was a simple way similar to just set an event handler for the button and call Close();. But, how can I do that or why it is not working for me?

View code:

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();
}

Button 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>

Upvotes: 0

Views: 1148

Answers (1)

loopedcode
loopedcode

Reputation: 4893

Close isn't recognized in your event handler because there is probably no method called Close in your current class. If you want to call main window's close method you can use:

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

Above is not a good way to do this and does not align with MVVM pattern. Which relates to your second question. Without seeing remaining part of your code, its hard to say why command binding isn't working. My guess you haven't wired up the commands properly for it to fire. You will need to ensure that you have created your RelayCommand instance and your command properties are correctly set.

Upvotes: 2

Related Questions