我正在使用简单的图片库制作程序。在这个图库中,所选图片必须返回图片的字符串路径,我知道哪一个被选中。我喜欢将此路径字符串从子ViewModel返回到MainViewModel。
稍后我还有一个例子,我在创建新文件,文件需要创建一个名称。我喜欢从子ViewModel返回此名称字符串到MainViewModel。
我想要的(如果可能的话)是将字符串从ChildViewModel返回到MainViewModel。这是用DialogResult做的吗?
现在我正在尝试返回一个布尔值,我知道是否"取消"或者"好的"被压了。如果" OK"按下(所以DialogResult为true)将从子和close形式获取字符串。如果"取消"将被按下我将关闭表格。我有问题,我的代码总是返回相同的值。我的代码出了什么问题?
MainWindowViewModel:
private void OpenGalleryClicked()
{
var gy = new GalleryViewModel();
var gallery = new GalleryWindow();
gallery.DataContext = gy;
var result = gallery.ShowDialog();
if (result.Value && result.HasValue)
{
MessageBox.Show("OK", "OK", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Not OK", "Not OK", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
GalleryViewModel
public class GalleryViewModel : ViewModelBase, ICloseable
{
private string _path = @"C:\Users\blabla\Documents\visual studio 2015\Projects\GalleryExample\GalleryExample\Images\";
public ICommand GetImage { get; set; }
public ICommand CloseGallery { get; set; }
public event EventHandler<RequestCloseEventArgs> RequeRequestClosestCloseEventArgs;
public GalleryViewModel()
{
GetImage = new RelayCommand(param => GetImageClicked(new RequestCloseEventArgs(true)));
CloseGallery = new RelayCommand(param => InvokeRequestCloseDialog(new RequestCloseEventArgs(false)));
SearchForImages();
}
private void InvokeRequestCloseDialog(RequestCloseEventArgs e)
{
var handler = RequeRequestClosestCloseEventArgs;
if (handler != null)
handler(this, e);
}
private void GetImageClicked(RequestCloseEventArgs e)
{
var handler = RequeRequestClosestCloseEventArgs;
if (handler != null)
handler(this, e);
}
...
GalleryWindow.xaml.cs
public partial class GalleryWindow : Window
{
public GalleryWindow()
{
InitializeComponent();
Loaded += (s, e) =>
{
if (DataContext is ICloseable)
{
(DataContext as ICloseable).RequeRequestClosestCloseEventArgs += (_, __) => Close();
}
};
}
}
ICloseable:
internal interface ICloseable
{
event EventHandler<RequestCloseEventArgs> RequeRequestClosestCloseEventArgs;
}
public class RequestCloseEventArgs : EventArgs
{
public RequestCloseEventArgs(bool dialogResult)
{
this.DialogResult = dialogResult;
}
public bool DialogResult { get; set; }
}
如有任何问题请询问。谢谢!