0
我正在學習WPF並調查DataBinding。我想看看如何在XAML而不是C#中指定DataBinding,但不知道下面的例子中我做錯了什麼。無法讓XAML中的DataBinding正常工作
(我知道有很多這樣的問題,但我已經通過了他們所有,但不能得到任何工作建議)。
<Window x:Class="DataBinding2.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"
x:Name="theMainWindow"
xmlns:local="clr-namespace:DataBinding2"
>
<StackPanel>
<WrapPanel Name="WrapPanel1" Orientation="Vertical" Margin="10" >
<!--// Tried this but get error: The type 'local:person2' was not found. -->
<WrapPanel.DataContext>
<local:person2 />
</WrapPanel.DataContext>
<TextBlock Text="{Binding Path=FirstName}"/>
</WrapPanel>
namespace DataBinding2
{
public partial class MainWindow : Window
{
public Person person2;
public MainWindow()
{
person2 = new Person()
{
FirstName = "Bob",
};
InitializeComponent();
// This works - but want to know what alternative is to do it in XAML
//WrapPanel1.DataContext = person2;
}
}
public class Person
{
public string FirstName { get; set; }
public int Age { get; set; }
}
嘗試將您的person2包裝在屬性Person2中,並在XAML中引用它。 WPF是關於屬性的。 –