关于DataContext的

weikeni19 weikeni19 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
请问我书上的(2)怎么用?我自己写了一段代码 但没显示 该怎么改?或者你们写一段代码给我看看 谢谢了 高分献上
书上的内容:

我的代码是这样的
XAML代码是这样的 我在项目里新建了一个窗口Window1
<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBox Text="{Binding Id}"/>
</Grid>
</Window>
--------------------------------------------------------------------------
MainWindow的Xaml代码是这样的:
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:WpfApplication5"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<StackPanel.DataContext>
<sys:Student Id="6"/>
</StackPanel.DataContext>
<Button Click="Button_Click_1"/>
</StackPanel>
</Window>
----------------------------------------------------------------------
C#后台代码是这样的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace WpfApplication5
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
Window1 a = new Window1();
a.ShowDialog();
}
}
public class Student
{
public int Id { get; set; }
}
}


...全文
评论 5
收藏 已收藏
分享
返回顶部
weikeni19
WPF/Silverlight 8,757 成员 12,031 内容