代码之家  ›  专栏  ›  技术社区  ›  luka

WPF未加载控件

  •  2
  • luka  · 技术社区  · 8 年前

    我写了一个非常简单的用户控件

    这里是XAML代码

    <UserControl x:Name="Test1" x:Class="WpfAppXtesting.UserControl1"
             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:WpfAppXtesting"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800" Loaded="Test1_Loaded">
    
    <Grid x:Name="GridRoot" Background="Aqua">
        <TextBlock x:Name="status" HorizontalAlignment="Left" Height="137" Margin="100,137,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="483" FontSize="48"/>
    
    </Grid>
    

    下面是代码

    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
            this.GridRoot.DataContext = this;
        }
    
        private void UserControl1_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "Connected":
                    status.Text = ((App)sender).Connected.ToString() ; 
                    break;
            }
        }
    
        private void Test1_Loaded(object sender, RoutedEventArgs e)
        {
            (Application.Current as App).PropertyChanged += UserControl1_PropertyChanged;
        }
    }
    

    问题是,当在同一项目的窗口中导入此控件时,设计模式会收到此错误。

    NullReferenceException:对象引用未设置为对象的实例。

    如果我负责这个项目,一切都很好。

    如果我在加载方法中对行进行了注释

    控件在设计模式下显示正确。

    知道吗? 谢谢

    1 回复  |  直到 8 年前
        1
  •  2
  •   user1672994    8 年前

    不要假设 Application.Current 您的应用程序是否在设计时。例如,当您使用 Expression Blend ,当前是表达式混合。在设计时, MainWindow 不是应用程序的主窗口。通常,导致用户/客户控件在设计时失败的操作包括以下内容。

    1. 将电流强制转换为应用程序的自定义子类。
    2. 将主窗口强制转换为窗口的自定义子类。

    下面是两种为设计时编写代码的方法。第一种方法是写 防守的 通过检查空条件进行编码。第二种方法是通过调用 GetIsInDesignMode 方法。你可以读到 获取IsInDesignMode here .

    解决方案1:

    private void Test1_Loaded(object sender, RoutedEventArgs e)
    {
        var app = Application.Current as App;
        if( app != null) 
        {
            app.PropertyChanged += UserControl1_PropertyChanged;
        } 
    }
    

    解决方案2:

    private void Test1_Loaded(object sender, RoutedEventArgs e)
    {
       if (!DesignerProperties.GetIsInDesignMode(this))
        {
            // Design-mode specific functionality
            (Application.Current as App).PropertyChanged += UserControl1_PropertyChanged;
        }
    
    }
    
    推荐文章