从其他班级设置标签的内容

时间:2014-08-13 08:16:00

标签: .net wpf vb.net

我有一个简单的问题。 我想从其他类改变标签的内容但不会发生

这是我的XML代码:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="Imię:" HorizontalAlignment="Left" Margin="47,50,0,0" VerticalAlignment="Top"/>
        <Label Content="Nazwisko:" HorizontalAlignment="Left" Margin="19,81,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tbImie" HorizontalAlignment="Left" Height="23" Margin="87,52,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="tbNazwisko" HorizontalAlignment="Left" Height="23" Margin="87,83,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="btnDodaj" Content="Dodaj" HorizontalAlignment="Left" Margin="233,65,0,0" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="btnWyswietl" Content="Wyświetl" HorizontalAlignment="Left" Margin="332,65,0,0" VerticalAlignment="Top" Width="75"/>
        <Label x:Name="labelOsoba" Content="a" HorizontalAlignment="Left" Margin="82,189,0,0" VerticalAlignment="Top" Height="27" Width="141"/>

    </Grid>
</Window>

这是我的MainWindow代码:

Class MainWindow

    Dim imie As String
    Dim nazwisko As String

    Dim osoba As Osoby = New Osoby()



    Private Sub btnDodaj_Click(sender As Object, e As RoutedEventArgs) Handles btnDodaj.Click
        imie = tbImie.Text
        nazwisko = tbNazwisko.Text
        osoba.dodajOsobe(imie, nazwisko)
    End Sub


    Private Sub btnWyswietl_Click(sender As Object, e As RoutedEventArgs) Handles btnWyswietl.Click
        osoba.wyswietlOsoby()
    End Sub
End Class

这是我的课程,其中设置标签不起作用:

    Public Class Osoby

        Dim listaOsob As List(Of String)
        Dim glowneOkno As MainWindow


        Public Sub New()
            listaOsob = New List(Of String)
        End Sub


        Public Sub dodajOsobe(ByVal imie As String, ByVal nazwisko As String)
            listaOsob.Add(imie)
        End Sub


        Public Sub wyswietlOsoby()
            glowneOkno = New MainWindow()
            glowneOkno.labelOsoba.Content = listaOsob(0)  'here, it doesn't work
        End Sub

    End Class

PS。抱歉,波兰名称:)

1 个答案:

答案 0 :(得分:0)

它没有更新主窗口对象。因为您正在第二个类中创建主窗口对象的新实例。而不是你在Second类的构造函数中可以做的,传递这个Mainwindow对象(已经创建),并在你的函数中更改标签的内容,它肯定会对你有用。

解决方案

MainWindow.xaml.cs

public Mainwindow()
{
   InitializeComponent();
   Dim osoba As Osoby = New Osoby(this)

}

在第二课

//现在在第二个对象的构造函数中

public void osoby(MainWindow obj)
{
  this.glowneOkno = obj;
}

因为我是c#guy。请使用在线工具将其转换为相应的vb。