先准备一个ViewModel
1 public class ViewModel 2 { 3 private ViewModel() 4 { 5 Names = new List<string>() 6 { 7 "A", 8 "B", 9 "C", 10 "D", 11 "E", 12 "F", 13 }; 14 } 15 16 private static readonly ViewModel _instance = new ViewModel(); 17 18 public static ViewModel Instance => _instance; 19 20 public bool IsChecked { get; set; } 21 22 public List<string> Names { get; set; } 23 }
界面绑定VM
DataContext="{x:Static local:ViewModel.Instance}"
界面代码
1 <Window 2 x:Class="ControlTemplate绑定ViewModel属性.MainWindow" 3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 5 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 6 xmlns:local="clr-namespace:ControlTemplate绑定ViewModel属性" 7 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 8 Title="MainWindow" 9 Width="800" 10 Height="450" 11 DataContext="{x:Static local:ViewModel.Instance}" 12 FontSize="20" 13 mc:Ignorable="d"> 14 <Grid> 15 <ListView ItemsSource="{Binding Names}"> 16 <ListView.ItemTemplate> 17 <DataTemplate> 18 <StackPanel Orientation="Horizontal"> 19 <TextBlock 20 Margin="10,0" 21 HorizontalAlignment="Left" 22 Text="{Binding}" /> 23 <!-- 控件模板绑定ViewModel --> 24 <CheckBox 25 HorizontalAlignment="Left" 26 Content="选择" 27 IsChecked="{Binding Path=DataContext.IsChecked, RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}}" /> 28 </StackPanel> 29 </DataTemplate> 30 </ListView.ItemTemplate> 31 </ListView> 32 </Grid> 33 </Window>
运行效果