我如何添加按钮/插件如果且仅当它'还没有
本文关键字:还没有 如果 插件 何添加 添加 按钮 | 更新日期: 2023-09-27 17:54:54
我改变代码使用堆栈面板,并得到这个,从重复点击
我如何实现它,以便它只添加按钮/插件,如果它是空白的,而不是添加它们,如果堆栈面板已经填充??
下面是后面的代码:using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using PluginContracts;
using System;
using System.IO;
using Microsoft.Win32;
namespace SimplePlugin
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Dictionary<string, IPlugin> _Plugins;
public MainWindow()
{
InitializeComponent();
}
private void AssembleComponents(object sender)
{
_Plugins = new Dictionary<string, IPlugin>();
//ICollection<IPlugin> plugins = PluginLoader.LoadPlugins("Plugins");
ICollection<IPlugin> plugins = GenericPluginLoader<IPlugin>.LoadPlugins("Plugins");
foreach(var item in plugins)
{
Button b = new Button();
//if exists an object,
if (b!= null)
{
//delete that object, instantiate new object
_Plugins.Add(item.Name, item);
b.Content = item.Name;
b.Click += b_Click;
stackPanel.Children.Add(b);
b = null;
//PluginGrid.Children.Add(b);
}
}
}
private void b_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if(b != null)
{
string key = b.Content.ToString();
if(_Plugins.ContainsKey(key))
{
IPlugin plugin = _Plugins[key];
plugin.Do();
}
}
}
private void addPlugin_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Filter = "All files (*.*)|*.*|DLL files (*.dll)|*.dll|CS Files (*.cs)|*.cs";
if (fileDialog.ShowDialog() == true)
{
string filename = fileDialog.FileName;
var ext = System.IO.Path.GetExtension(filename);
// ListBox lbFiles = new ListBox();
//this.Controls.Add(lbFiles);
//lbFiles.Size = new System.Drawing.Size(200, 100);
//lbFiles.Location = new System.Drawing.Point(10, 10);
lbFiles.Items.Add(System.IO.Path.GetFileName(filename));
//
CopyToDir(filename);
}
}
//private void lbFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
//{
// AssembleComponents();
//}
private void CopyToDir(string filename)
{
// txtBox.Text = "Hello World";
string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
Console.WriteLine(path);
//Check the directory exists
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
FileInfo fi = new FileInfo(filename);
if (!File.Exists(System.IO.Path.Combine(path, fi.Name)))
{
File.Copy(fi.FullName, System.IO.Path.Combine(path, fi.Name));
}
}
catch (Exception ex)
{
throw ex;
}
}
//Approach 1
//if exists an object, delete that object, instantiate new object
private void lbFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AssembleComponents(sender);
}
//Approach 2
private void ClearBtn_Click(object sender, RoutedEventArgs e)
{
lbFiles.Items.Clear();
}
}
}
你可以使用Count方法来检查你的stackpanel是否包含项目,试试这样做:
if (stackpanel.Children.Count <= 0)
{
_Plugins.Add(item.Name, item);
stackPanel.Children.Add(b);
}