簡體   English   中英

從不同類調用的C#(WPF)方法

[英]C# (WPF) methods calling from different classses

我對編碼非常陌生。 當涉及輸入變量時,將方法從B調用到類A時遇到問題。 請解釋為什么a.PrintAfromB(); 給我0值 如何克服這種情況。 我看到一些使用MVVM的示例。 但是在現階段,這些對我來說非常復雜。 好像我得到輸入變量不正確或調用方法不正確。 我很累,無法解決這個問題就無法前進。

主要

public partial class MainWindow : Window {
    public MainWindow(){
        InitializeComponent();
        this.DataContext = this;
    }

        B b = new B();
        A a = new A();

    private void Button_Click(object sender, RoutedEventArgs e) {
        b.Bat = double.Parse(one.Text);
        b.PrintB();
        a.PrintAfromB();
        a.PrintAfromBB();
    }
}

一種

class A
{
    double Apple { get; set; }    
    B b1 = new B();           
    public void PrintAfromB() {

        Console.WriteLine("Calling method from B where input involved: "+b1.CallB());
    }

    public void PrintAfromBB() {

        Console.WriteLine("Calling method from B where input not involved: " + b1.CallBB());
    }
}

public class B{
   public double Bat { get; set; }
   public double k = 0;

    public void PrintB(){
        k = Bat;
        Console.WriteLine("test input value" +k);
    }

    public double CallB(){
        return 10 * Bat;
    }

    public double CallBB(){
        return 10 * 10;
    }
}

XAML

<Window x:Class="inputtest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:inputtest"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBlock HorizontalAlignment="Left" Margin="62,141,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    <TextBox x:Name="one" HorizontalAlignment="Left" Height="23" Margin="198,134,0,0" TextWrapping="Wrap" Text="10" VerticalAlignment="Top" Width="120"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="380,263,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

</Grid>

問題在於,A類的另一個實例B與Main中的實例不同。

要使A打印輸入的內容,應將B實例放入A。

因此,使A如下所示:

class A
{
  B b1;
  public A(B b){
    b1 = b;
  }

  double Apple { get; set; }    

  public void PrintAfromB() {
    Console.WriteLine("Calling method from B where input involved: "+ b1.CallB());
  }

  public void PrintAfromBB() {
    Console.WriteLine("Calling method from B where input not involved: " + b1.CallBB());
  }
}

然后像下面這樣更改Main:

public partial class MainWindow : Window {
  public MainWindow(){
    InitializeComponent();
    this.DataContext = this;
  }

  B b = new B();
  A a = new A(b);

  private void Button_Click(object sender, RoutedEventArgs e) {
      b.Bat = double.Parse(one.Text);
      b.PrintB();
      a.PrintAfromB();
      a.PrintAfromBB();
  }
}

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM