WPF之设置DataContext的三种方式
1.代码设置
在Window初始化时设置,如下:
public MainWindow() {InitializeComponent();this.DataContext = new MainViewModel(); }
优点:简单方便。缺点:在xaml中没有代码提示
2.在xaml设置
如果viewmodel不在默认的命名空间中,需要先引入命名空间
<Window x:Class="wpf_textBlock.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:wpf_textBlock"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.DataContext> <local:MainViewModel></local:MainViewModel> </Window.DataContext>
这种方式最常见,推荐使用
3.使用d:DataContext指定
在设计时绑定,会有代码提示,不会影响运行时的数据。需要使用一或二方法绑定数据才会真的生效。
<Window x:Class="wpf_textBlock.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:wpf_textBlock"mc:Ignorable="d"d:DataContext="{d:DesignInstance local:MainViewModel}"Title="MainWindow" Height="450" Width="800">