WPF中,如何通过binding显示后台的数据?
代码如下XAML<Windowx:Class="WpfApplication7.MainWindow"xmlns="http://schemas.microsoft.co...
代码如下
XAML
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication7"
Title="MainWindow" Height="350" Width="525">
<StackPanel x:Name="stackPanel">
<StackPanel.DataContext>
<local:Person></local:Person>
</StackPanel.DataContext>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
<TextBlock Text="{Binding Path=Age}"></TextBlock>
</StackPanel>
</Window>
后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication7
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Person p1 = new Person();
p1.Age = 5;
p1.Name = "Tim";
}
}
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
}
问题,如何将在后台定义的对象p1的Age和Name在TextBlock中显示? 展开
XAML
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication7"
Title="MainWindow" Height="350" Width="525">
<StackPanel x:Name="stackPanel">
<StackPanel.DataContext>
<local:Person></local:Person>
</StackPanel.DataContext>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
<TextBlock Text="{Binding Path=Age}"></TextBlock>
</StackPanel>
</Window>
后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication7
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Person p1 = new Person();
p1.Age = 5;
p1.Name = "Tim";
}
}
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
}
问题,如何将在后台定义的对象p1的Age和Name在TextBlock中显示? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询