c# - 在WPF-MVVM中的“当前窗口”中保存并关闭

标签 c# wpf mvvm mvvm-light

我的窗口中有两个按钮,保存,保存和关闭。如果用户单击“保存”,则可以成功保存详细信息。当用户单击“保存并关闭”时,我无法弄清楚如何关闭窗口。这是我保存的代码

<telerik:RadButton x:Name="button_Save" Content="Save" Command="{Binding SaveProductCommand}" CommandParameter="{Binding ElementName=ProductName, Path=Text}" />

这是我的中继命令。
public ICommand SaveProductCommand
{
  get 
  {
    return new RelayCommand<string>(SaveProductExecute);
  } 
 }

我的第一个问题:

我们可以为Save和Save&Close再传递一个参数True或false吗?这样我们就只能对两者使用一个中继命令?

第二个问题:

保存后如何关闭当前窗口?

最佳答案

好问题..这里的关键是使用Action。看一下我的样本

我们将尽量减少编码。

Can we pass one more parameter True or false for Save and Save&Close ? So that we can use only one Relay Command for both ?



由于您还没有提到如何传递是非值,所以我提供了一个列表框,其中包含两个字符串项TrueFalse

如果选择了true,则仅执行命令的一部分;如果选择了false,则将执行命令中的两种方法。
  • 使用按钮创建 View 列表框
      <ListBox x:Name="items">
        <System:String>True</System:String>
        <System:String>False</System:String>
      </ListBox>
    
    <Button Content="MyButton" Command="{Binding Path=MyCustomCommand}" 
    CommandParameter="{Binding SelectedItem,ElementName=items}"/> 
    
  • 创建ViewModel,即 MyViewModel.cs
    public class MyViewModel : INotifyPropertyChanged
    {
    
       public Action CloseAction { get; set; }
       public ICommand MyCustomCommand { get; set; }
    
    
       public MyViewModel()
       {
          MyCustomCommand = new RelayCommand(new Action<object>(MyFunction));
       }
    
    
       private void MyFunction(object MyCommandParameter)
       {
        if (Convert.ToString(MyCommandParameter) == "True")
        {
            MessageBox.Show("Save Executed");
        }
        else
        {
            MessageBox.Show("Save Execcuted");
            CloseAction();
        }
    }
    
  • 在代码隐藏中
      public partial class MainWindow : Window
      {
         public MainWindow()
         {
            InitializeComponent();
            MyViewModel mv = new MyViewModel();
            this.DataContext = mv;
    
            if (mv.CloseAction == null)
                mv.CloseAction = new Action(() => this.Close());
          }
      }
    
  • 关于c# - 在WPF-MVVM中的“当前窗口”中保存并关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236915/

    相关文章:

    c# - Form1 Load Event 仅执行第一条语句

    c# - RaisePropertyChanged 在 TwoWay Bound 属性上抛出 StackOverflow 异常

    c# - WPF:如何循环遍历 ContextMenu 以重新排列其中的项目或将菜单项作为子项添加到菜单项

    .net - 适用于 Windows Forms 和 WPF 的商业控制套件 : which can be recommended?

    c# - 在 WPF 用户控件中附加 ICommand

    c# - 在 C# 中从 DB.Null 转换为十进制的任何方法

    c# - 显示过滤器 C#

    c# - C#中如何获取调用方法的属性

    c# - WPF,Caliburn.Micro和Dapper组合框

    WPF 和 MVVM : Changing data binding converter at runtime