我正在从头开始重写WinForms应用程序(它必须是WinForms,因为我想使用WPF和MVVM).这样做我选择使用MVC模式并尽可能使用依赖注入(DI)来提高可测试性,可维护性等.
我遇到的问题是使用MVC和DI.使用baisic MVC模式,控制器必须能够访问视图,并且视图必须能够访问控制器(有关WinForms示例,请参阅此处); 这导致使用Ctor-Injection时的循环引用,这是我的问题的关键.首先请考虑我的代码
Program.cs(WinForms应用程序的主要入口点):
static class Program
{
[STAThread]
static void Main()
{
FileLogHandler fileLogHandler = new FileLogHandler(Utils.GetLogFilePath());
Log.LogHandler = fileLogHandler;
Log.Trace("Program.Main(): Logging initialized");
CompositionRoot.Initialize(new DependencyModule());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(CompositionRoot.Resolve<ApplicationShellView>());
}
}
Run Code Online (Sandbox Code Playgroud)
DependencyModule.cs
public class DependencyModule : NinjectModule
{
public override void Load()
{
Bind<IApplicationShellView>().To<ApplicationShellView>();
Bind<IDocumentController>().To<SpreadsheetController>();
Bind<ISpreadsheetView>().To<SpreadsheetView>();
}
}
Run Code Online (Sandbox Code Playgroud)
CompositionRoot.cs
public class CompositionRoot
{
private static IKernel ninjectKernel;
public static void Initialize(INinjectModule module)
{
ninjectKernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return …Run Code Online (Sandbox Code Playgroud) c# model-view-controller dependency-injection ninject winforms
全部,我有一个返回List的方法.此方法用于根据名称返回SQL StoredProcedures,Views和Functions的参数.我想要做的是创建一个对象列表并将此列表返回给调用者.方法如下
private List<T> GetInputParameters<T>(string spFunViewName)
{
string strSql = String.Format(
"SELECT PARAMETER_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.PARAMETERS " +
"WHERE SPECIFIC_NAME = '{0}' AND PARAMETER_MODE = 'IN';",
spFunViewName);
List<string[]> paramInfoList = new List<string[]>();
DataTable paramDt = Utilities.DTFromDB(conn, "InputParmaters", strSql);
if (paramDt != null)
{
Converter<DataRow, string[]> rowConverter =
new Converter<DataRow, string[]>(Utilities.RowColConvert);
paramInfoList = Utilities.ConvertRowsToList<string[]>(paramDt, rowConverter);
}
else
return null;
// Build the input parameter list.
List<T> paramList = new List<T>();
foreach (string[] paramInfo in paramInfoList)
{
T t = new T(paramInfo[NAME], …Run Code Online (Sandbox Code Playgroud) 总而言之,我已经获得了多线程大型C#应用程序的工作.要做到这一点,我选择使用async/ await.我清楚地知道使用的IProgress<T>报告进度,以在UI(我们称之为"推"信息发送到UI),但我还需要从UI到"拉"的数据(在我的情况下的SpreadsheetGear工作簿,它包含数据).正是这种双向互动,我想要一些建议......
目前我触发了一个click事件来开始处理,代码具有以下结构:
CancellationTokenSource cancelSource;
private async void SomeButton_Click(object sender, EventArgs e)
{
// Set up progress reporting.
IProgress<CostEngine.ProgressInfo> progressIndicator =
new Progress<CostEngine.ProgressInfo>();
// Set up cancellation support, and UI scheduler.
cancelSource = new CancellationTokenSource();
CancellationToken token = cancelSource.Token;
TaskScheduler UIScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// Run the script processor async.
CostEngine.ScriptProcessor script = new CostEngine.ScriptProcessor(this);
await script.ProcessScriptAsync(doc, progressIndicator, token, UIScheduler);
// Do stuff in continuation...
...
}
Run Code Online (Sandbox Code Playgroud)
然后ProcessScriptAsync,我有以下内容:
public async Task ProcessScriptAsync( …Run Code Online (Sandbox Code Playgroud) c# multithreading task-parallel-library async-await .net-4.5
我有以下内容 DataGrid
<DataGrid CanUserDeleteRows="True"
CanUserAddRows="True"
SelectedItem="{Binding SelectedResource, Mode=TwoWay}"
ItemsSource="{Binding Path=Resources, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
IsAsync=True}"> ... </<DataGrid>
Run Code Online (Sandbox Code Playgroud)
我使用MVVM模式绑定到一个ObservableCollection<ResourceViewModel> Resources,这很好用.我有一个添加新行的按钮,这是通过添加一个新ResourceViewModel的Resources集合来完成的- 很棒.现在,我希望用户能够点击空的最后一行,这会自动在中创建一个新记录DataGrid.
我已经确定的DataGrid有CanUserAddRows=True.我确保我绑定的collection Resources(ResourceViewModel)中的类有一个默认构造函数(没有参数),并且我确保集合类型不是readonly.当用户点击最后一行时,默认构造函数会触发,但要正确实例化ResourceViewModel需要的新对象,请引用该Resources集合的网格...
我想我可以AttachedCommand在CellBeginEdit事件中使用和然后在ResourceViewModel那里添加一个新的可观察集合,有没有一种标准的方法来做到这一点?
请注意,我已阅读以下问题,这些对我没有帮助
编辑.事实证明,由于WPF中的错误,我在执行此操作时遇到了问题DataGrid.见Nigel Spencer的博客.但是,他的修复目前对我不起作用......
我试图以CloudBlockBlob的形式从Azure存储下载文件.我想允许用户选择下载文件的放置位置,因此我编写了以下代码来执行此操作
[AllowAnonymous]
public async Task<ActionResult> DownloadFile(string displayName)
{
ApplicationUser user = null;
if (ModelState.IsValid)
{
user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
// Retrieve storage account and blob client.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.AppSettings["StorageConnectionString"]);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(
VisasysNET.Utilities.Constants.ContainerName);
// If the container does not exist, return error.
if (container.Exists())
{
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
if (blob.Name.CompareNoCase(displayName))
{
string contentType = String.Format(
"application/{0}",
Path.GetExtension(displayName).TrimStart('.'));
// No need …Run Code Online (Sandbox Code Playgroud) 我对自定义控件相对较新(在代码中从头开始编写控件 - 不仅仅是对现有控件进行样式化).我正在复制YouTube视频控件,你知道那个......
首先,我想开发"时间轴"(透明灰色条,显示视频的当前位置,并允许用户拖动以更改位置).随着预览面板和所有其余的后来......
我目前控制部分渲染,悬停动画和缩放工作非常好...
但是,我正在努力编写正确的代码以允许我拖动"拇指".当我尝试处理我的左键单击Ellipse代表我的拇指Canvas时,根据WPF文档,包含火灾的离开事件,所以没有投诉,我只是不知道如何实现我想要的,实际上如果我已经做的是正确的方法.
代码:
[ToolboxItem(true)]
[DisplayName("VideoTimeline")]
[Description("Controls which allows the user navigate video media. In addition is can display a " +
"waveform repesenting the audio channels for the loaded video media.")]
//[TemplatePart(Name = "PART_ThumbCanvas", Type = typeof(Canvas))]
[TemplatePart(Name = "PART_TimelineCanvas", Type = typeof(Canvas))]
[TemplatePart(Name = "PART_WaveformCanvas", Type = typeof(Canvas))]
[TemplatePart(Name = "PART_PreviewCanvas", Type = typeof(Canvas))]
[TemplatePart(Name = "PART_Thumb", Type = typeof(Ellipse))] // Is this the right thing to be doing?
public class …Run Code Online (Sandbox Code Playgroud) 我试图将DataGridView绑定到List,MyObject看起来像
class MyObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
//List<MyObject> objects;
grid.Columns[0].DataPropertyName = "Property1";
grid.DataSource = objects;
Run Code Online (Sandbox Code Playgroud)
我只想显示一个属性,但我将另一列添加到我的DataGridView,其中也显示了Property2.如何防止它被添加?
我有一个richTextBox我用来执行一些语法高亮.这是一个小编辑工具,所以我没有编写自定义语法高亮显示器 - 而是使用Regexs并使用事件的事件处理程序检测输入延迟时更新Application.Idle:
Application.Idle += new EventHandler(Application_Idle);
Run Code Online (Sandbox Code Playgroud)
在事件处理程序中,我检查文本框是否处于非活动状态:
private void Application_Idle(object sender, EventArgs e)
{
// Get time since last syntax update.
double timeRtb1 = DateTime.Now.Subtract(_lastChangeRtb1).TotalMilliseconds;
// If required highlight syntax.
if (timeRtb1 > MINIMUM_UPDATE_DELAY)
{
HighlightSyntax(ref richTextBox1);
_lastChangeRtb1 = DateTime.MaxValue;
}
}
Run Code Online (Sandbox Code Playgroud)
但即使对于相对较小的亮点RichTextBox,它也会大量闪烁,而且没有任何richTextBox.BeginUpdate()/EndUpdate()方法.为了解决这个问题,我找到了汉斯帕斯特(Hans Passant)类似困境的答案(汉斯帕斯特从未让我失望!):
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class MyRichTextBox : RichTextBox
{
public void BeginUpdate()
{
SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);
}
public …Run Code Online (Sandbox Code Playgroud) 鉴于下面的类,要在备用线程上启动闪屏:
public partial class SplashForm : Form
{
private static Thread _splashThread;
private static SplashForm _splashForm;
public SplashForm()
{
InitializeComponent();
}
// Show the Splash Screen (Loading...)
public static void ShowSplash()
{
if (_splashThread == null)
{
// Show the form in a new thread.
_splashThread = new Thread(new ThreadStart(DoShowSplash));
_splashThread.IsBackground = true;
_splashThread.Start();
}
}
// Called by the thread.
private static void DoShowSplash()
{
if (_splashForm == null)
_splashForm = new SplashForm();
// Create a new message pump …Run Code Online (Sandbox Code Playgroud) 首先我看到IEqualityComparer是匿名类型,那里的答案没有回答我的问题,因为显而易见的原因是我需要一个IEqualityComparer不IComparer用于Linq的Distinct()方法.我也检查了其他答案,这些都没有解决方案......
问题
我有一些代码来操纵和从中提取记录 DataTable
var glext = m_dtGLExt.AsEnumerable();
var cflist =
(from c in glext
orderby c.Field<string>(m_strpcCCType),
c.Field<string>(m_strpcCC),
c.Field<string>(m_strpcCCDesc),
c.Field<string>(m_strpcCostItem)
select new
{
CCType = c.Field<string>(m_strpcCCType),
CC = c.Field<string>(m_strpcCC),
CCDesc = c.Field<string>(m_strpcCCDesc),
CostItem = c.Field<string>(m_strpcCostItem)
}).Distinct();
Run Code Online (Sandbox Code Playgroud)
但是我需要使用不同的方法来区分大小写.这里扔我的是使用匿名类型.
尝试解决方案1
如果我有SomeClass具体的物体,我显然可以做到
public class SumObject
{
public string CCType { get; set; }
public string CC { get; set; }
public string CCDesc { get; set; }
public string CostItem { get; set; …Run Code Online (Sandbox Code Playgroud) c# ×10
wpf ×2
.net ×1
.net-4.5 ×1
asp.net-mvc ×1
async-await ×1
azure ×1
controls ×1
data-binding ×1
datagrid ×1
datagridview ×1
generics ×1
linq ×1
mvvm ×1
ninject ×1
richtextbox ×1
winforms ×1