阅读 126

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

先准备一个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     
15         "{Binding Names}">
16             
17                 
18                     "Horizontal">
19                         <TextBlock
20                             Margin="10,0"
21                             HorizontalAlignment="Left"
22                             Text="{Binding}" />
23                         
24                         <CheckBox
25                             HorizontalAlignment="Left"
26                             Content="选择"
27                             IsChecked="{Binding Path=DataContext.IsChecked, RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}}" />
28                     
29                 
30             
31         
32     
33 

运行效果

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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐