首页 > 代码库 > WPF-设置窗体的DataContext

WPF-设置窗体的DataContext

1. 窗体的XAML设置DataContext

view

 1 <Window x:Class="MVVM_Binding_ViewModelMainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:vm="clr-namespace:MVVM_Binding_ViewModel.ViewModel"
 5         Title="MainWindow" Height="350" Width="525">
 6     <Window.DataContext>
 7         <vm:MainViewModel/>
 8     </Window.DataContext>
 9     <Grid>
10         <TextBlock HorizontalAlignment="Left" Text="{Binding TextBlockStr}" VerticalAlignment="Top" Height="52" Width="153"/>
11     </Grid>
12 </Window>

ViewModel

 1 namespace MVVM_Binding_ViewModel.ViewModel
 2 {
 3     public class MainViewModel
 4     {
 5         public string TextBlockStr
 6         {
 7             get
 8             {
 9                 return "TextBlockStr";
10             }
11         }
12     }
13 }

 

WPF-设置窗体的DataContext