【问题标题】:Have trouble understanding wpf visual studio setup无法理解 wpf Visual Studio 设置
【发布时间】:2016-05-11 15:48:50
【问题描述】:

我有一个由 Visual Studio 设置的 wpf 项目。我正在尝试创建 MVP 类,但我无法访问我创建的这些类中的任何 xaml 属性(例如 textBox1.text 或 label.Content)

他们给我的文件是 MainWindow.xaml.cs、MainWindow.xaml 和其他一些文件。我可以访问 MainWindow.xaml.cs 中的那些 xaml 属性。但在我的 view.cs 中,它显示 'textBox' does not exist in the current content。感谢任何额外的细节和信息

MainWINdow.xaml.cs:

namespace myApp
{
public partial class MainWindow : Window
{
    private Model model;
    public MainWindow()
    {
        InitializeComponent();
        //initialize the storage
        model= new Model();
    }

    /// <summary>
    /// clear the textbox for user input
    /// </summary>
    private void clearInput()
    {
        textBox1.Text = ""; //these works fine
        textBox2.Text = "";
        textBox3.Text = "";
    }

[...]
}

view.cs:

namespace myApp
{
public interface IView
{
    void clearInput();
}

public class PView: IView
{
    public void clearInput()
    {
        textBox1.Text = ""; //error
        textBox2.Text = "";
        textBox3.Text = "";
    }
 }

【问题讨论】:

标签: c# wpf visual-studio-2010 xaml


【解决方案1】:

您需要为 XAML 文件中的控件(文本框等)命名,如下所示

<TextBlock Name="textblock1" .....

然后在你的代码文件中你可以访问 textblock1

编辑

但是,这些控件始终是私有的,因此对其他类不可见。要公开数据,您需要尝试以下操作:

public string TextBlockText
{
   get { return textblock1.Text; }
}

然后在你的其他类中你可以使用

var text = MainWindow.TextBlockText;

EDIT2

或者,您可以像这样公开这些控件

<TextBox x:Name="textBox1" x:FieldModifier="public" />

【讨论】:

  • 是的,我有,这就是为什么我可以在 mainwindow.xaml.cs 中访问它们。但我无法在我创建的 view.cs 中访问它们
  • 所以我必须在我的 MainWindow.xaml.cs 中创建这些方法才能让视图类访问它?看起来很乱。也许我没有正确表达我的问题,我做了一个编辑,你能看一下吗?谢谢
  • 是的,您不应该从另一个类访问您的 XAML 中的控件。如果你想实现 MVP,你需要创建这些访问器属性。为什么不尝试迁移到 MVVM,这是大多数 WPF 完成的方式,部分原因是这个原因。 Howe3ver,我添加了一个编辑来显示您需要的解决方法
  • 肯定的。先看一下简单的 MVVM 实现,如果你必须做 MVP,请查看我的答案的附加编辑
  • @user308553(根据我使用过的以及我看到它的建议).xaml.cs 通常只包含所需的最少代码隐藏(通常 none 除了自动生成初始化),您的视图模型将是一个单独的类,并使用绑定和数据上下文与 xaml 进行通信。
猜你喜欢
  • 2015-02-08
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2019-03-03
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多