[英]Why doesn't property syntax work when dynamically adding TextBox
I'm trying to learn how to add WPF controls at runtime. 我正在尝试学习如何在运行时添加WPF控件。 Below is a simple example with question to follow:
以下是一个简单的示例,其中包含以下问题:
XAML XAML
<Window x:Class="BindAndDynamicPractice.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Name="splMain">
<Button Name="btnAddMore" Click="btnAddMore_Click">Add Another</Button>
</StackPanel>
</Window>
C# C#
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Shapes;
namespace BindAndDynamicPractice
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void btnAddMore_Click(object sender, RoutedEventArgs e)
{
AnotherTextBox mybindingtest = new AnotherTextBox();
splMain.Children.Add(mybindingtest.PropTextBox);
}
}
public class AnotherTextBox
{
System.Windows.Controls.TextBox _newTextBox = new TextBox();
public TextBox PropTextBox { get; set; }
}
}
This compiles but I get a runtime error which I think has something to do with attempting to use a property. 这样可以编译,但是出现运行时错误,我认为这与尝试使用属性有关。 I believe this because when I change the AnotherTextBox class to the following:
我相信这是因为当我将AnotherTextBox类更改为以下内容时:
public class AnotherTextBox
{
System.Windows.Controls.TextBox _newTextBox = new TextBox();
public TextBox PropTextBox()
{
return _newTextBox;
}
}
And then update btnAddMore_Click: 然后更新btnAddMore_Click:
public void btnAddMore_Click(object sender, RoutedEventArgs e)
{
AnotherTextBox mybindingtest = new AnotherTextBox();
splMain.Children.Add(mybindingtest.PropTextBox());
}
Now this works as it should. 现在,它可以正常工作了。
So why does using a full get method work but using a property not? 那么,为什么使用完全获取方法却不能使用属性呢?
Thanks 谢谢
You don't have a property, you have a method. 您没有属性,但是有方法。 Therefore you must call it using method syntax.
因此,您必须使用方法语法来调用它。 Are you by chance coming from Java?
您是否偶然来自Java?
A method: 一个方法:
public TextBox PropTextBox()
{
return _newTextBox;
}
A property: 属性:
public TextBox PropTextBox {
get { return _newTextBox(); }
}
There is a tutorial on properties here: http://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx 这里有关于属性的教程: http : //msdn.microsoft.com/zh-cn/library/aa288470(v=vs.71).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.