我的窗口中有两个按钮,保存,保存和关闭。如果用户单击“保存”,则可以成功保存详细信息。当用户单击“保存并关闭”时,我无法弄清楚如何关闭窗口。这是我保存的代码
<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 ?
由于您还没有提到如何传递是非值,所以我提供了一个列表框,其中包含两个字符串项
True
和False
。如果选择了
true
,则仅执行命令的一部分;如果选择了false
,则将执行命令中的两种方法。 <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}"/>
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/