自定义UserControl中的标签内容未更新

时间:2012-10-26 13:41:01

标签: c# wpf custom-controls

我创建了一个由12个标签组成的自定义UserControl。

enter image description here

现在,当程序加载时,需要更改带有“默认”作为内容的标签。

// This is called in my main forms constructor, right before InitializeComponent()
public void ShowRigInfo()
{
    // This is here because if I try to call PopluateLabels, I get an "Object not
    // set to an instance of object" error
    grdRigInfo = new RigInfoGrid();

    var contractor = SplitString("contractor", _rigInfo);
    var projectName = SplitString("projectname", _rigInfo);
    var location = SplitString("location", _rigInfo);
    var operatorName = SplitString("operator", _rigInfo);
    var rigName = SplitString("rigsite_name", _rigInfo);
    var rigManager = SplitString("rigmanager", _rigInfo);

    grdRigInfo.PopulateLabels(contractor, projectName, location, operatorName,
                              rigName, rigManager);
    }

// A public method of my custom UserControl to update label content
public void PopulateLabels(string contractor, string project, string location, 
                           string operatorName, string rigName, string manager)
{
    lblContractor.Content = contractor;
    lblProjectName.Content = project;
    lblLocation.Content = location;
    lblOperator.Content = operatorName;
    lblRigName.Content = rigName;
    lblRigManager.Content = manager;            
}

我的问题是,如何在程序启动时更新标签?感谢您的帮助。

修改

我试图在我的主要表单的ShowRigInfo()之前和之后调用InitializeComponent()。他们都没有改变标签。

编辑2

好的,我在实际看到答案之前解决了这个问题。我所做的是将我的ShowRigInfo()移动到我的自定义UserControl中,而不是我的主窗体。我不知道为什么我从一开始就没有这样做,但确实如此。我将查看答案的DataBinding部分。谢谢你们。

3 个答案:

答案 0 :(得分:3)

好吧,因为这是WPF,我建议将这些标签绑定到某种支持(实现)INotifyPropertyChanged的模型中的属性。

如果你谷歌用这些话,你会走很长的路。

答案 1 :(得分:2)

为什么不在Loaded事件处理程序

中尝试它

答案 2 :(得分:1)

AD.Net是对的:将初始设置放入Loaded事件中。在构造函数中,您可以使用局部变量,但通常不能使用可视元素。一旦“Loaded”事件被触发,您的所有UI组件都应该可以使用。

但是,我强烈建议您在标签上使用DataBinding和DataContext,而不是通过公共方法填充它们。最后,如果您开始使用datagrids,treeviews和listviews,您将了解如何围绕Binding构建WPF系统。