Ali Adlavaran
Ali Adlavaran

Reputation: 3735

How do i bind a button to close command in window style

i want to create a custom close button in window style that it relyes window's close command. i wrote something like this:

<Style x:Key="WindowsGeneralStyle"  TargetType="Window">
   ...
    <Setter Property="Template" >
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Window}">
                <Grid>
                     ...
                     <Button x:Name="closebtn" Command={Binding Close} ... />
                </Grid> 
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

but it didn't work. How do this?

Upvotes: 0

Views: 1065

Answers (2)

Ali Adlavaran
Ali Adlavaran

Reputation: 3735

I resolved problem. I create a partial class for our ResourceDictionary and in the behind code i handled Close button click event:

ResourceDictionary XAML file:

    <ResourceDictionary ...  x:Class="MyNameSpace.WindowStyle">
    ...
    <Style x:Key="WindowsGeneralStyle"  TargetType="Window">
            <Setter Property="Template" >
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Window}">
                        <Grid>
                             ...
                             <Button x:Name="closebtn"  Click="CloseBTN_Clicked" ... />
                        </Grid> 
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</ResourceDictionary>

and behind code:

namespace MyNameSpace
{
    public partial class WindowStyle
    {
        private void CloseBTN_Clicked(object sender, RoutedEventArgs e)
        {
            Window.GetWindow(((FrameworkElement)e.Source)).Close();
        }
    }
}

Now,It works pretty well!

Upvotes: 1

brunnerh
brunnerh

Reputation: 184296

{Binding Close} tries to bind to a Close command in the current DataContext, you probably want something like {x:Static ApplicationCommands.Close}.

Upvotes: 0

Related Questions