gpt4 book ai didi

wpf - 如果验证失败,请不要关闭窗口 - 在 WPF 中

转载 作者:行者123 更新时间:2023-12-03 10:50:27 24 4
gpt4 key购买 nike

我是 WPF 和 MVVM 的初学者。
我有一个简单的 wpf 窗口,我在其中添加了 2 个值。我正在使用命令绑定(bind)
在添加按钮中。

这是我的按钮 xaml 代码

<Button Content="OK" Name="btn_OK" Command="{Binding AddShutterType}" />

这个命令写在我的 View 模型中,我也在做一些验证
但我的问题是,如果验证失败或成功,我的窗口不会关闭!!
如果我给“this.close”窗口按钮单击事件,那么它总是关闭。
我的要求是如果验证失败则保留窗口,如果验证成功则关闭。这该怎么做?

这是我的 View 模型代码,其中包含验证部分。
    private ICommand _AddShutterType;

public ICommand AddShutterType
{
get
{
if (_AddShutterType == null)
{
_AddShutterType = new DeligateCommand.DelegateCommand(delegate()
{
ShutterNameToAdd.Trim();
ShutterCodeToAdd.Trim();

StringBuilder SB = new StringBuilder();
if (ShutterCodeToAdd == "")
{
SB.Remove(0, SB.Length);
SB.Append("Please type in a Code for the shutter.");
throw new ArgumentException(SB.ToString());
}

if (ShutterCodeToAdd.Length > 10)
{
SB.Remove(0, SB.Length);
SB.Append("Shutter type code size cannot be more than 5");
throw new ArgumentException(SB.ToString());
}

if (ShutterNameToAdd == "")
{
SB.Remove(0, SB.Length);
SB.Append("Please type in a Name for the shutter.");
throw new ArgumentException(SB.ToString());
}

Model.AddShutterType(ShutterCodeToAdd, ShutterNameToAdd);
});
}
return _AddShutterType;
}
}

请任何人帮助我..

最佳答案

我的解决方案是在 vm 中保存 View 的 ref,但这将是一个接口(interface);

例如。

public View : UserControl, IView
{
void IView.Close()
{
this.Close();
}
}

public ViewModel
{
public IView View{get;set;}

public void CommandImpl()
{
if (Validated())
View.Close();
}
}

希望这可以帮助。

关于wpf - 如果验证失败,请不要关闭窗口 - 在 WPF 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5510452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com