我有两种形式a&湾表格a是主要表格,其中一个按钮点击事件表格b显示为一个小窗口。在弹出窗口(表单b)上,我可以选择图像。我需要做的是当我点击弹出窗口的保存按钮(表格b),形成一个(主窗体)背景图像应该设置为通过弹出窗体(b)选择的图像。
我尝试过以下代码,但是.Parent,this.Owner all为弹出窗体(b)返回null。我已将表格指定为MDI。
this.Owner.BackgroundImage = pictureBoxBackground.Image;
this.Parent.BackgroundImage = pictureBoxBackground.Image;
答案 0 :(得分:1)
我要做的是在表单b中有一个像这样的公共Image属性:
private Image image;
public Image SelectedImage
{
get
{
return image;
}
}
然后我会添加一个button_Click事件(或用于确认选择的任何内容)。此事件将关闭表单并设置返回图像。
private void Button_Click(object sender, EventArgs e)
{
image = [Whatever Image variable that you want to return];
Close();
}
使FormB看起来像这样。
public class FormB : Form
{
//[...]Stuff
private Image image;
public Image SelectedImage
{
get
{
return image;
}
}
private void Button_Click(object sender, EventArgs e)
{
image = [Whatever Image variable that you want to return];
Close();
}
}
最后,将其用于FormA的背景图像。只需遵循以下程序即可。
public void ChangeBackground()
{
FormB b = new FormB();
b.ShowDialog();
this.BackgroundImage = b.SelectedImage;
}
答案 1 :(得分:0)
如果您希望弹出窗口弹出对话框并返回图像,则可以将图像放在属性中。例如:
public class Parent : Form
{
var popup = new Popup();
var result = popup.ShowDialog();
if(result == DialogResult.OK)
{
this.BackgroundImage = popup.Image;
}
}
public class Popup : Form
{
private void SelectImage()
{
Image = pictureBoxBackground.Image;
}
public string Image {get;set;}
}
如果您希望弹出窗口作为常规窗口打开并且能够同时使用父级,则需要使用事件,更多信息here
public class Parent : Form
{
var popup = new Popup();
popup.BackgroundImageChanged += (sender, args) => this.BackgroundImage = args.Image;
//...
}
public class Popup : Form
{
public event EventHandler<ImageChangedEventArgs> BackgroundImageChanged;
private void SelectImage()
{
// ...
OnBackgroundImageChanged(pictureBoxBackground.Image);
}
private void OnBackgroundImageChanged(string image)
{
if(BackgroundImageChanged != null)
{
var e = new ImageChangedEventArgs(image);
BackgroundImageChanged(this, e);
}
}
}
public class ImageChangedEventArgs : EventArgs
{
public ImageChangedEventArgs(string image)
{
Image = image;
}
public string Image { get; private set; }
}