我正在学习WPF并调查DataBinding。我想看看如何在XAML中而不是在C#中指定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; }
}
答案 0 :(得分:2)
您可以将DataContext设置为仅实例,而不是直接设置为XAML中某些实例中的属性。
要首先使用使person2成为属性,因为绑定仅适用于属性,至少对象为对象:
public Person person2 { get; set; }
然后您可以在XAML中设置DataContext,如下所示:
<WrapPanel Name="WrapPanel1" Orientation="Vertical" Margin="10"
DataContext="{Binding person2, ElementName=theMainWindow}">