WPF DataContext与Binding的关系
在前台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(); } }
运行结果
源码下载地址https://github.com/lizhiqiang0204/DataContext-and-Bingding.git
有朋友会有疑问,一个UI文件的DataContext只能指定一个类吗?不,是可以指定多个类的。
我们新建一个类ClassB
其他文件不用动,只需修改UI文件
<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> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid> <Grid.DataContext> <local:ClassA/> </Grid.DataContext> <Label Content="{Binding myLabel}"/> </Grid> <Grid Grid.Row="1"> <Grid.DataContext> <local:ClassB/> </Grid.DataContext> <Label Content="{Binding myLabel}"/> </Grid> </Grid> </Window>
多类之间如何互相访问呢?参考https://www.cnblogs.com/lizhiqiang0204/p/12582510.html