首页 > Windows开发 > 详细

WPF 控件模板中绑定后台属性

时间:2021-07-27 15:36:56      阅读:103      评论:0      收藏:0      [点我收藏+]

先准备一个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>

运行效果

技术分享图片

WPF 控件模板中绑定后台属性

原文:https://www.cnblogs.com/AtTheMoment/p/15065176.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!