C#(WPF)方法从不同的类调用

时间:2017-12-15 05:01:45

标签: c# wpf oop methods

我对编码很新。当涉及输入变量时,从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();
    }
}
  

A

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>

1 个答案:

答案 0 :(得分:1)

问题是A Class的另一个B实例与Main中的实例不同。

要打印A输入的内容,您应该将B实例放入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();
  }
}
希望它有所帮助。

相关问题