问题描述:
近期项目需要在VSTO插件中设计WinForms界面,该界面需要实现一个功能:当WinForms从外部应用中获取数据后,将其传递到editbox显示栏内。项目开发中遇到以下问题:WinForms中实例化Ribbon后,再引用其中的函数或Invalidate功能,在运行时会报错:System.NullReferenceException:“未将对象引用设置到对象的实例。”
Forms.cs中:
Ribbon myribbon1 = new Ribbon();
myribbon1.getArasLoginUser();
Ribbon.cs中:
public string passArasLoginUser()
{
_loginuser = Form1.arasLoginUserID;
return _loginuser;
}
public void getArasLoginUser()
{
_loginuser = passArasLoginUser();
ribbon.InvalidateControl("editBox7");
}
报错出现在ribbon.InvalidateControl("editBox7")处。经过排查发现,该方法导致ribbon为null。
解决方案:
方案一:
在ThisAddin.cs中申明公共Ribbon变量。
public Ribbon myRibbon = null;
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
//return new Ribbon(); 默认
myRibbon = new Ribbon();
return myRibbon;
}
在Form1.cs中做如下引用:
Globals.ThisAddIn.myRibbon.getArasLoginUser();
方案二:
Ribbon.cs中:
public class Ribbon : Office.IRibbonExtensibility
public Office.IRibbonUI ribbon;
internal static Office.IRibbonUI solutionRibbon;
public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
solutionRibbon = ribbonUI;
}
internal static string _loginuser = "null";
public string loginUser(Office.IRibbonControl control)
{
return _loginuser;
}
Form1.cs中:
Ribbon._loginuser = arasLoginUserID;
Ribbon.solutionRibbon.InvalidateControl("editBox7");
标签:Invalidate,Office,ribbon,WinForms,VSTO,loginuser,cs,public,Ribbon
From: https://www.cnblogs.com/blog-fx/p/18054807