C#从另一个类更改TextBox背景

时间:2017-11-25 22:45:40

标签: c# wpf class

我试图在PING之后从类中更改TextBox_Drukarki_Model背景。代码:

MainWindow:MetroWindow

private void Button_Drukarki_Sprawdz_Click(object sender, RoutedEventArgs e)
{
    DrukarkaPing test = new DrukarkaPing(TextBox_Drukarki_IPNS.Text);
    test.CheckPing();
}

MainForm以外的另一个课程

class DrukarkaPing
{
    private string adresip;
    private MainWindow _form;


    public DrukarkaPing(MainWindow MetroWindow)
    {
        _form = MetroWindow;
    }

    public DrukarkaPing(string adresip)
    {
        this.adresip = adresip;
    }

    public async void CheckPing()
    {
        try
        {
            Ping PingZapytanie = new Ping();
            PingReply PingOdp = PingZapytanie.Send(adresip);

            if (PingOdp.Status == IPStatus.Success)
            {
                _form.TextBox_Drukarki_Model.Background = new SolidColorBrush(Colors.Green);
            }
            else
            {
                var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
                if (window != null)
                    await window.ShowMessageAsync("Błąd!", "Błędny adres IP lub Netbios.");
            }
        }
        catch (Exception e)
        {
            var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
            if (window != null)
                await window.ShowMessageAsync("Błąd!", e.Message);
        }
    }
}

它几乎正常工作但是当IPStatus.Success时,catch会显示异常: &#34;对象引用未设置为对象的实例&#34;。 我不知道要改变什么。我在构造函数中尝试了与MetroWindow,MainWindow或TextBox_Drukarki_Model的各种组合。

更新立即开始工作。

主要

DrukarkaPing Sprawdznext = new DrukarkaPing(TextBox_Drukarki_IP.Text, TextBox_Drukarki_IPNS.Text);
Sprawdznext.CheckPing(TextBox_Drukarki_IP);

CS:

private string adresip;
private string test;

public TextBox TextBox_Drukarki_IP { get; set; }
public TextBox TextBox_Drukarki_IPNS { get; set; }

public DrukarkaPing(string adresip, string test)
{
    this.adresip = adresip;
    this.test = test;
}

public async void CheckPing(TextBox TextBox_Drukarki_IP)
{
    try
    {
        if (test == "" || test == " ")
        {
            return;
        }
        else
        {
            Ping PingZapytanie = new Ping();
            PingReply PingOdp = PingZapytanie.Send(adresip);

            if (PingOdp.Status == IPStatus.Success)
            {
                TextBox_Drukarki_IP.Background = new SolidColorBrush(Colors.Green);
            }
            else
            {
                TextBox_Drukarki_IP.Background = new SolidColorBrush(Colors.Red);
            }
        }
    }
    catch (Exception e)
    {
        var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
        if (window != null)
            await window.ShowMessageAsync("Błąd!", e.Message);
    }
}

0 个答案:

没有答案