在Form1顶部:
public String LabelText
{
get { return label4.Text; }
set { label4.Text = value; }
}
然后在用户控件
中public int countf = 0;
private void AddFiles(string[] files, int startIndex, int count)
{
while (count-- > 0)
{
countf++;
listBox.Items.Add(files[startIndex + count]);
Form1.Label
}
}
但是当我尝试访问它时,LabelText不存在。 如果我将创建form1的新实例,它不会再重写form1构造函数吗?
我想从用户控件更新label4。
这是完整的Form1代码:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace Search_files
{
public partial class Form1 : Form
{
private DirectorySearcher directorySearcher;
private System.Windows.Forms.TextBox searchText;
private System.Windows.Forms.Label searchLabel;
private System.Windows.Forms.Button searchButton;
public String LabelText
{
get { return label4.Text; }
set { label4.Text = value; }
}
public Form1()
{
//
// Required for Windows Forms designer support.
//
InitializeComponent();
//
// Add any constructor code after InitializeComponent call here.
//
}
private void searchButton_Click(object sender, System.EventArgs e)
{
directorySearcher.SearchCriteria = searchText.Text;
searchLabel.Text = "Searching...";
directorySearcher.BeginSearch();
}
private void directorySearcher_SearchComplete(object sender, System.EventArgs e)
{
searchLabel.Text = string.Empty;
}
}
}
这是我认为在开始时不需要的完整用户控制代码:
如果我在这里添加参数类型标签:
private void AddFiles(string[] files, int startIndex, int count, Label textlabel)
{
while (count-- > 0)
{
countf++;
listBox.Items.Add(files[startIndex + count]);
}
}
我添加了参数Label textlabel 然后我收到了错误:
fileListDelegate = new FileListDelegate(AddFiles);
'AddFiles'没有重载匹配委托'DirectorySearcher.FileListDelegate'
这是用户控件的完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace Search_files
{
public partial class DirectorySearcher : UserControl
{
// Define a special delegate that handles marshaling
// lists of file names from the background directory search
// thread to the thread that contains the list box.
private delegate void FileListDelegate(string[] files, int startIndex, int count);
private ListBox listBox;
private string searchCriteria;
private bool searching;
private bool deferSearch;
private Thread searchThread;
private FileListDelegate fileListDelegate;
private EventHandler onSearchComplete;
public DirectorySearcher()
{
listBox = new ListBox();
listBox.Dock = DockStyle.Fill;
Controls.Add(listBox);
fileListDelegate = new FileListDelegate(AddFiles);
onSearchComplete = new EventHandler(OnSearchComplete);
}
public string SearchCriteria
{
get
{
return searchCriteria;
}
set
{
// If currently searching, abort
// the search and restart it after
// setting the new criteria.
//
bool wasSearching = Searching;
if (wasSearching)
{
StopSearch();
}
listBox.Items.Clear();
searchCriteria = value;
if (wasSearching)
{
BeginSearch();
}
}
}
public bool Searching
{
get
{
return searching;
}
}
public event EventHandler SearchComplete;
/// <summary>
/// This method is called from the background thread. It is called through
/// a BeginInvoke call so that it is always marshaled to the thread that
/// owns the list box control.
/// </summary>
/// <param name="files"></param>
/// <param name="startIndex"></param>
/// <param name="count"></param>
///
public int countf = 0;
private void AddFiles(string[] files, int startIndex, int count, Label textlabel)
{
while (count-- > 0)
{
countf++;
listBox.Items.Add(files[startIndex + count]);
}
}
public void BeginSearch()
{
// Create the search thread, which
// will begin the search.
// If already searching, do nothing.
//
if (Searching)
{
return;
}
// Start the search if the handle has
// been created. Otherwise, defer it until the
// handle has been created.
if (IsHandleCreated)
{
searchThread = new Thread(new ThreadStart(ThreadProcedure));
searching = true;
searchThread.Start();
}
else
{
deferSearch = true;
}
}
protected override void OnHandleDestroyed(EventArgs e)
{
// If the handle is being destroyed and you are not
// recreating it, then abort the search.
if (!RecreatingHandle)
{
StopSearch();
}
base.OnHandleDestroyed(e);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
if (deferSearch)
{
deferSearch = false;
BeginSearch();
}
}
/// <summary>
/// This method is called by the background thread when it has finished
/// the search.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnSearchComplete(object sender, EventArgs e)
{
if (SearchComplete != null)
{
SearchComplete(sender, e);
}
}
public void StopSearch()
{
if (!searching)
{
return;
}
if (searchThread.IsAlive)
{
searchThread.Abort();
searchThread.Join();
}
searchThread = null;
searching = false;
}
/// <summary>
/// Recurses the given path, adding all files on that path to
/// the list box. After it finishes with the files, it
/// calls itself once for each directory on the path.
/// </summary>
/// <param name="searchPath"></param>
private void RecurseDirectory(string searchPath)
{
// Split searchPath into a directory and a wildcard specification.
//
string directory = Path.GetDirectoryName(searchPath);
string search = Path.GetFileName(searchPath);
// If a directory or search criteria are not specified, then return.
//
if (directory == null || search == null)
{
return;
}
string[] files;
// File systems like NTFS that have
// access permissions might result in exceptions
// when looking into directories without permission.
// Catch those exceptions and return.
try
{
files = Directory.GetFiles(directory, search);
}
catch (UnauthorizedAccessException)
{
return;
}
catch (DirectoryNotFoundException)
{
return;
}
// Perform a BeginInvoke call to the list box
// in order to marshal to the correct thread. It is not
// very efficient to perform this marshal once for every
// file, so batch up multiple file calls into one
// marshal invocation.
int startingIndex = 0;
while (startingIndex < files.Length)
{
// Batch up 20 files at once, unless at the
// end.
//
int count = 20;
if (count + startingIndex >= files.Length)
{
count = files.Length - startingIndex;
}
// Begin the cross-thread call. Because you are passing
// immutable objects into this invoke method, you do not have to
// wait for it to finish. If these were complex objects, you would
// have to either create new instances of them or
// wait for the thread to process this invoke before modifying
// the objects.
IAsyncResult r = BeginInvoke(fileListDelegate, new object[] { files, startingIndex, count });
startingIndex += count;
}
// Now that you have finished the files in this directory, recurse for
// each subdirectory.
string[] directories = Directory.GetDirectories(directory);
foreach (string d in directories)
{
RecurseDirectory(Path.Combine(d, search));
}
}
/// <summary>
/// This is the actual thread procedure. This method runs in a background
/// thread to scan directories. When finished, it simply exits.
/// </summary>
private void ThreadProcedure()
{
// Get the search string. Individual
// field assigns are atomic in .NET, so you do not
// need to use any thread synchronization to grab
// the string value here.
try
{
string localSearch = SearchCriteria;
// Now, search the file system.
//
RecurseDirectory(localSearch);
}
finally
{
// You are done with the search, so update.
//
searching = false;
// Raise an event that notifies the user that
// the search has terminated.
// You do not have to do this through a marshaled call, but
// marshaling is recommended for the following reason:
// Users of this control do not know that it is
// multithreaded, so they expect its events to
// come back on the same thread as the control.
BeginInvoke(onSearchComplete, new object[] { this, EventArgs.Empty });
}
}
}
}
form1设计师:
命名空间Search_files { 部分类Form1 { /// ///所需的设计变量。 /// private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.searchButton = new System.Windows.Forms.Button();
this.searchText = new System.Windows.Forms.TextBox();
this.searchLabel = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.directorySearcher = new Search_in_files.DirectorySearcher();
this.SuspendLayout();
//
// searchButton
//
this.searchButton.Location = new System.Drawing.Point(8, 16);
this.searchButton.Name = "searchButton";
this.searchButton.Size = new System.Drawing.Size(88, 40);
this.searchButton.TabIndex = 0;
this.searchButton.Text = "&Search";
this.searchButton.Click += new System.EventHandler(this.searchButton_Click);
//
// searchText
//
this.searchText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.searchText.Location = new System.Drawing.Point(104, 24);
this.searchText.Name = "searchText";
this.searchText.Size = new System.Drawing.Size(378, 20);
this.searchText.TabIndex = 1;
this.searchText.Text = "c:\\*.cs";
//
// searchLabel
//
this.searchLabel.ForeColor = System.Drawing.Color.Red;
this.searchLabel.Location = new System.Drawing.Point(104, 48);
this.searchLabel.Name = "searchLabel";
this.searchLabel.Size = new System.Drawing.Size(176, 16);
this.searchLabel.TabIndex = 3;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(299, 51);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 13);
this.label3.TabIndex = 4;
this.label3.Text = "Number of files ";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(385, 51);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(35, 13);
this.label4.TabIndex = 5;
this.label4.Text = "label4";
//
// directorySearcher
//
this.directorySearcher.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.directorySearcher.Location = new System.Drawing.Point(8, 72);
this.directorySearcher.Name = "directorySearcher";
this.directorySearcher.SearchCriteria = null;
this.directorySearcher.Size = new System.Drawing.Size(474, 200);
this.directorySearcher.TabIndex = 2;
this.directorySearcher.SearchComplete += new System.EventHandler(this.directorySearcher_SearchComplete);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(494, 291);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.searchLabel);
this.Controls.Add(this.directorySearcher);
this.Controls.Add(this.searchText);
this.Controls.Add(this.searchButton);
this.Name = "Form1";
this.Text = "Search Directories";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
private ListViewCostumControl listViewCostumControl1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
}
}
答案 0 :(得分:1)
将标签作为参数传递给UserControl
public int countf = 0;
public void AddFiles(string[] files, int startIndex, int count, Label textLabel)
{
while (count-- > 0)
{
countf++;
listBox.Items.Add(files[startIndex + count]);
textLabel.Text = "";
}
}
或将其设置为
public Label TextLabel{ get; set;}
然后在InitializeComponents()
UserControl.TextLabel = myLabel;