在Class中使用MainForm中的对象

时间:2013-11-28 12:35:57

标签: c# wpf

我正在用C#WPF编写一个应用程序。

我在这里遇到一个小问题。

在class.cs中,我有一行:

MessageBox.Show("Cancelled sending !");

在我的表格上,我有一个radioButton1。

我怎样才能像

那样
if (radioButton1.IsChecked == true)
{
    MessageBox.Show("Cancelled sending !");
}

因为当我尝试它时,它找不到radioButton1

我尝试过不同的方式,但我找不到怎么做。

4 个答案:

答案 0 :(得分:0)

如果我理解你的错误,那你就试图在class.cs中访问radioButton的值,对吧?如果是这样,您可以创建一个公共属性,它封装了您的radiobutton-checked-property。

这看起来像:

public bool IsRadioButtonChecked
{
   get{return radioButton1.IsChecked;}
}

在class.cs中,你需要一个窗口实例。

答案 1 :(得分:0)

您在表单上创建的单选按钮存储在MainForm类的私有变量中。因此,它是其他类无法访问的。

您可以将其转换为公共变量,但这不是一个非常好的方法,在任何情况下,当您在表单上添加/删除/调整大小控件时,表单设计器都会覆盖它。

更好的解决方案是通过构造函数将单选按钮的引用传递给另一个类,或者作为检查单选按钮状态的方法的参数(如果由表单调用它) )。

例如:

public class MyClass {
    private mRbutton;

    public MyClass(RadioButton rbutton) {
        mRbutton = rbutton;
        // Rest of the construction code...
    }

    //
    // ... Rest of the class code ...
    //

    public void MessageShowingMethod() {
        if (mRbutton.IsChecked == true) {
            MessageBox.Show("Cancelled sending !");
        }
    }
}

答案 2 :(得分:0)

试试吧。在您的主要表格中:

if (radioButton1.IsChecked == true)
{
  int checked = 1;
}

callMyMethod(checked);

然后在你的class.cs中:

public callMyMethod(int checked)
{
  if (checked == 1)
  {
    MessageBox.Show("Cancelled sending !");
  }
  else
  {
    MessageBox.Show("Something else");
  }
}

答案 3 :(得分:0)

使用WPF时,除其他外,我们还有WindowUserControl个类。这些是部分类,这意味着它们中包含多个文件。有一个.xaml文件,我们定义了UI和.xaml.cs文件后面的代码,我们可以访问我们在相关.xaml中定义的命名的 UI元素文件。 您永远不应该访问任何其他类中的UI元素

要访问代码隐藏文件中的UI元素,必须先在.xaml文件中命名:

<RadioButton Name="RadioButton" />

然后,仅在代码隐藏文件中,您可以使用该名称访问它:

if (RadioButton.IsChecked)
{
    MessageBox.Show("Cancelled sending !");
}

再一次,你永远不应该访问任何其他类的UI元素