如何在WPF中更新TextBlock的文本

时间:2017-07-04 14:47:51

标签: c# wpf xaml

每当我尝试将文本更新为TextBlock时。抛出以下异常:"对象引用设置为null"。

我的代码:

<UniformGrid Grid.Row="1" Grid.Column="1" Height="30" >
    <Border DockPanel.Dock="Top">
        <TextBlock Foreground="White" TextAlignment="Justify" VerticalAlignment="Center" x:Name="TbcontentName" FontWeight="SemiBold"  />
    </Border>
</UniformGrid>

我在另一个窗口中使用此TextBlock

if((setMainWindowCall.Try("TbcontentName") as TextBox).Text != null)
    (setMainWindowCall.FindName("TbcontentName") as TextBox).Text = _nameOfUc;

1 个答案:

答案 0 :(得分:0)

您正在使用... as TextBoxTbcontentName定义为XAML中的TextBlock,因此动态转换返回null并在尝试时抛出NullPointerException访问.Text - 属性。在代码中将as TextBox更改为as TextBlock或更改

<TextBlock ... x:Name="TbcontentName" ... />

<TextBox ... x:Name="TbcontentName" ... />
相关问题