在前台UI创建一个Label绑定到myLabel
<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="300" Width="500"> <Grid> <Label Content="{Binding myLabel}"/> </Grid> </Window>
在后台代码赋值myLabel
using System.Windows; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private string label = "我的标签"; public string myLabel { get { return label; } set { label = value; } } public MainWindow() { InitializeComponent(); DataContext = this; } } }
运行如下
这里的DataContext = this到底是什么呢?调试运行发现DataContext 其实就是MainWindow类
如果我们自己新建一个类,让DataContext 等于这个新建的类是否可以呢?
内容如下
namespace WpfApp1 { public class ClassA { private string label = "新建类A的标签"; public string myLabel { get { return label; } set { label = value; } } } }
MainWindow.xaml.cs里的DataContext = this改成 DataContex = new ClassA();其他的不变
public partial class MainWindow : Window { private string label = "我的标签"; public string myLabel { get { return label; } set { label = value; } } public MainWindow() { InitializeComponent(); //DataContext = this; DataContext = new ClassA(); } }
运行结果