你好,我正在尝试掌握绑定。
XAML 代码:
<Window x:Class="WPF_SandBox.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 x:Name="stackPanel">
<TextBox x:Name="textBox_FirstName" Width="200" Margin="0,100,0,0" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />
<TextBox x:Name="textBox_LastName" Width="200" Margin="0,10,0,0" Text="{Binding Path=LastName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock x:Name="textBlock_FullName" Background="LightBlue" Width="200" Margin="0,10,0,0" Text="{Binding Path=FullName, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Window>
以下是C#代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Person person = new Person { FirstName = "Matt", LastName = "Smith" };
stackPanel.DataContext = person;
}
}
public class Person : INotifyPropertyChanged
{
string firstName;
string lastName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
OnPropertyChanged("FirstName");
OnPropertyChanged("FullName");
}
}
public string LastName
{
get { return lastName; }
set
{
lastName = value;
OnPropertyChanged("LastName");
OnPropertyChanged("FullName");
}
}
public string FullName
{
get
{
return String.Format("{0}, {1}",lastName,firstName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
当启动时,会显示一个有2个文本框和1个文本块的窗口。在窗口构造函数中,我创建了一个Person类的实例,并将stackPanel的DataContext分配给该实例。第一个文本框绑定到Person类的FirstName属性,第二个文本框绑定到LastName属性,最后的TextBlock只打印LastName属性和FirstName属性。正如我之前所说的,我在C#代码中设置了stackPanel的DataContext。如何在XAML中代替设置它?例如:
<StackPanel x:Name="stackPanel" DataContext="person">
<TextBox x:Name="textBox_FirstName" Width="200" Margin="0,100,0,0" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />
<TextBox x:Name="textBox_LastName" Width="200" Margin="0,10,0,0" Text="{Binding Path=LastName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock x:Name="textBlock_FullName" Background="LightBlue" Width="200" Margin="0,10,0,0" Text="{Binding Path=FullName, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
这样做不起作用,但是你可以看到我正在尝试在XAML中设置stackPanel的DataContext,我该如何做?
谢谢!