【发布时间】:2016-11-14 15:00:34
【问题描述】:
我尝试制作使用 UserControl (WPF) 的 Visual C# 应用程序。 默认情况下,VS Community 2015 C# 在与主程序相同的命名空间中生成 UserControl。它构建正确。 我想将它分开在它自己的命名空间中,以备将来重用。 我将自动生成的代码更改为在单独的命名空间中拥有 UserControl。
这是我的代码
用户控制
<UserControl x:Class="nsTabI2CMemRW.TabI2CMemRW"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:nsTabI2CMemRW"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="500">
<Grid>
<TextBox x:Name="AddrH"/>
<Label x:Name="AddrH_Label"/>
</Grid>
C#类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfApplication1; // This is my main app namespace
namespace nsTabI2CMemRW
{
/// <summary>
/// Interaction logic for TabI2CMemRW.xaml
/// </summary>
public partial class TabI2CMemRW : UserControl
{
public TabI2CMemRW()
{
//InitializeComponent();
((WpfApplication1.MainWindow)Application.Current.MainWindow).InitializeComponent(); //InitializeComponent();
}
}
}
主窗口 XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:UserControl="clr-namespace:nsTabI2CMemRW"
mc:Ignorable="d"
Title="MainWindow" Height="649.005" Width="620.667" ScrollViewer.CanContentScroll="True">
<Grid>
<TabControl x:Name="tabControl" Margin="0,0,0.4,0.2">
<TabControl.BindingGroup>
<BindingGroup/>
</TabControl.BindingGroup>
<TabItem x:Name="I2CMemReadWrite" Header="I2C Mem Read/Write">
<UserControl:TabI2CMemRW Margin="0,0,-0.2,278.2"/>
</TabItem>
<TabItem Header="TabItem">
<Button x:Name="button" Content="Button" Height="100" Width="75"/>
</TabItem>
</TabControl>
</Grid>
设计器显示错误“对象引用未设置为对象的实例”
<UserControl:TabI2CMemRW Margin="0,0,-0.2,278.2"/>
程序编译正常,但第一个选项卡(我的 UserControl 应该在的位置)是空白的。
【问题讨论】:
-
手动更改自动生成的代码通常不是一个好主意
-
您在 UserControl 中调用
MainWindow的InitializeComponent。这是行不通的,而且是错误的。而且我猜Application.Current.MainWindow是空的,因为您正在初始化 MainWindow -> 在您创建它时它不能存在。这就是为什么你最终会出现 NullRefernence 异常