如何在usercontrol中创建命令?

时间:2016-07-04 16:12:56

标签: c# wpf model-view-controller icommand

我正在使用模式MVC在WPF中开发我的第一个应用程序,我有一个问题。

我已经从类型Grid创建了一个usercontrol来创建一个自定义标题栏。此网格包含一个X按钮,我想将此按钮与命令相关联。

XAML中的我的网格:

<Grid x:Class="Views.TitleBarView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d"
      Style="{DynamicResource TitleStyleGrid}"
      x:Name="barView">

    <Label x:Name="labelAppName" Style="{DynamicResource TitleStyleLabel}" Content="Title"/>
    <Button x:Name="bttnClose" Style="{DynamicResource ButtonStyleCloseWindow}" Command="{Binding CloseCommand}"/>
    <Button x:Name="buttonMinimize" Style="{DynamicResource ButtonStyleMinimizeWindow}"  Command="{Binding MinimizeCommand}"/>
</Grid>

C#视图:

public partial class TitleBarView : Grid
{
    public TitleBarView()
    {
        InitializeComponent();
        TitleBarViewModel tvm = new TitleBarViewModel();
        tvm.RequestClose += (s, e) => this.Close();
        tvm.RequestMinimize+= (s, e) => this.Minimize();
        DataContext = tvm;
    }

    private void Close()
    {
            Window.GetWindow(this).Close();
    }

    private void Minimize()
    {
            Application.Current.MainWindow.WindowState = System.Windows.WindowState.Minimized;
    }
}

C#viewModel:

public class TitleBarViewModel : ViewModelBase, IRequestMinimizeViewModel, IRequestCloseViewModel
{
    private RelayCommand minimizeCommand;
    protected RelayCommand closeCommand;
    public event EventHandler RequestMinimize;
    public event EventHandler RequestClose;

    #region MinimizeCommand
    public ICommand MinimizeCommand
    {
        get
        {
            if (minimizeCommand == null)
            {
                minimizeCommand = new RelayCommand(Minimize);
            }
            return minimizeCommand;
        }
    }


    private void Minimize()
    {
        RequestMinimize(this, null);
    }
    #endregion

    #region CloseCommand
    public ICommand CloseCommand
    {
        get
        {
            if (closeCommand == null)
            {
                closeCommand = new RelayCommand(Close);
            }
            return closeCommand;
        }
    }

    protected void Close()
    {
        RequestClose(this, null);
    }
    #endregion
}

我看到不建议在userControl上设置DataContext。当我这样做时,我无法改变关闭命令。例如,我希望当主窗口调用命令关闭时,它调用Application.Current.Shutdown();而不是Application.Current.Shutdown();

我知道我有些不对劲,但我太难以解决。你能解释一下如何为userControl创建命令吗? (或者告诉我我做错了什么)

谢谢

0 个答案:

没有答案