我正在尝试创建一个包含自定义工具窗口的Visual Studio扩展,并在自定义工具窗口内为UserControl
使用数据绑定,但是好像UserControl
的{{1 }}在DataContext
的实例化与评估数据绑定之间进行更改。
这是应该创建带有UserControl
和UserControl
的自定义工具窗口的代码。 (在命令执行处理程序内)
DataContext
我的自定义工具窗口的构造函数如下:
object futureDataContext = new object();
YourUserControl toolWindowContent = new YourUserControl() { DataContext = futureDataContext };
// 0 for single instance tool window and true to create if it doesn't already exists
ToolWindowPane window = package.FindToolWindow(typeof(YourCustomToolWindow), 0, true);
window.Content = toolWindowContent;
到目前为止我所知道的:
-看来
// : base(null) has been auto generated at the file's creation public CustomTooWindow() : base(null) { // I have figured out that if this.Content isn't set when exiting the constructor we get a COM exception. // I'm assuming it's because Visual Studio must have something to display right after the custom tool window instantiation. this.Content = new YourUserControl(); }
返回的自定义工具窗口的实例与Visual Studio用于实际的实例不相同。-如果在
package.FindToolWindow()...
的构造函数中设置DataContext
的{{1}},则会保留-如果我在创建
YourUserControl
的实例化之后(在命令处理程序中而不是CustomToolWindow
的构造函数中)立即注册到DataContextChanged
,它将永远不会被触发。
UserControl
上肯定能有好的CustomToolWindow
吗?
编辑:
我找到了一种解决方法,但并不是很令人满意:在CustomToolWindow类中,我添加了以下内容:
DataContext
答案 0 :(得分:0)
似乎package.FindToolWindow()...返回的自定义工具窗口的实例与Visual Studio实际使用的实例不同。
您是说每次在下面调用代码时都会得到一个不同的实例吗?
ToolWindowPane window = package.FindToolWindow(typeof(YourCustomToolWindow), 0, true);
关于DataContext的更改,您提到了控件实例化和数据绑定之间的关系,您在哪里设置控件的DataContext,因为您没有在下面的usercontrol构造函数中传递任何参数。
// : base(null) has been auto generated at the file's creation
public CustomTooWindow() : base(null)
{
// I have figured out that if this.Content isn't set when exiting the constructor we get a COM exception.
// I'm assuming it's because Visual Studio must have something to display right after the custom tool window instantiation.
this.Content = new YourUserControl();
}