利刃 MVVMLight 4:绑定和绑定的各种使用场景

一、绑定:

 主要包含元素绑定和非元素绑定两种。

1、元素绑定,是绑定的最简单形式,源对象是WPF的元素,并且源对象的属性是依赖项属性。

根据我们之前的知识 ,依赖项属性具有内置的更改通知支持。所以当我们的源对象中改变依赖项属性的值时,会立即更新目标对象中的绑定属性。

以上篇的例子来重写,我们不用额外定义全局公开的属性来支持数据的显示。

如下:

1  "Vertical" HorizontalAlignment="Left" >
2         x:Name="WelcomeText" Width="200" Margin="10,10,0,0">
3         "{Binding ElementName=WelcomeText,Path=Text,StringFormat='Hello \{0\}'}" Margin="10,10,0,0">
4  

 

 TextBlock 绑定了名称为WelcomeText的元素,并且将Path指向Text属性,所以他的值会跟着 WelcomeText的变化而变化。

 

2、非元素类型绑定: 

2.1 Source属性:绑定具体的数据对象:如系统信息跟我们定义的资源数据。

定义Window下的全局资源

1     
2         "BorderBrush">Red
3     

应用到视图中

1   "10,50,0,0" Orientation="Vertical" >
2                 "{Binding Source={x:Static SystemFonts.IconFontFamily},Path=Source}" >
3                 "{Binding Source={StaticResource BorderBrush}}" Foreground="{Binding Source={StaticResource BorderBrush}}"  >
4   

结果:

 

 2.2 RelativeSource 属性:设置该属性 可以根据当前目标对象的相对关系指向源目标。比如获取当前对象的父亲对象、兄弟对象或者自身的其他属性等一些数据。

 1            "10,50,0,0" Orientation="Vertical" ToolTip="top" >
 2                 
 3                 "Horizontal" >
 4                     "150" Text="获取自身宽度:"  >
 5                     "200" Text="{Binding Path=Width,RelativeSource={RelativeSource Mode=Self}}" >
 6                 
 7                 
 8                 
 9                 "Horizontal" ToolTip="parent" >
10                     "150" Text="查找上一层ToolTip:" >  
11                     "{Binding Path=ToolTip,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type StackPanel}}}">
12                 
13                 
14                                 
15                 "Horizontal">
16                     "150" Text="查找上二层ToolTip:" >
17                     "{Binding Path=ToolTip,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type StackPanel},AncestorLevel=2}}">
18                                                
19 
20             

 代码很容易理解,这边在创建RelativeSource的时候,mode模式有四种类型:

 
  Mode成员名称 说明
  FindAncestor

引用数据绑定元素的父链中的上级。 这可用于绑定到特定类型的上级或其子类。 若要指定 AncestorType 和/或 AncestorLevel,这就是应使用的模式。

  PreviousData

允许在当前显示的数据项列表中绑定上一个数据项(不是包含数据项的控件)。

  Self

引用正在其上设置绑定的元素,并允许你将该元素的一个属性绑定到同一元素的其他属性上。

  TemplatedParent

引用应用了模板的元素,其中此模板中存在数据绑定元素。 这类似于设置 TemplateBindingExtension,且仅在 Binding 位于模板内部时适用。

 

 

 

 

 

 

 

注意:AncestorType 指得是查找的对象类型,AncestorLevel 代表搜索的层级的位置,如果是3,则忽略前两个发现的元素。

结果:

2.3 DataContext 属性:如果想将一个对象绑定到一个由多个元素组成的视图块或者复合元素中,用
DataContext 会更好开发和维护。如下
 1             "Vertical" DataContext="UInfo" >
 2                 
 3                 "Horizontal" >
 4                     "名称:" Width="100" >
 5                     
 6                 
 7 
 8                 "Horizontal">
 9                     "性别:" Width="100" >
10                     
11                 
12 
13             
 
   

 

二、绑定的各种使用场景:

数据绑定有普通的控件绑定应用:比如 下拉框、单选框、复选框、普通文本框 、日期框等;
复杂的绑定有数据列表绑定,用户控件信息绑定等,比如 ListBox,DataGrid,UserControl绑定等。

1、下拉框:

View代码:

 1                 "10,20,0,50">
 2                 "下拉框" FontWeight="Bold" FontSize="12" Margin="0,5,0,5" >
 3                 "Combbox" >                
 4                     "Left" Width="240">
 5                         "200" HorizontalAlignment="Left" ItemsSource="{Binding CombboxList}" SelectedItem="{Binding CombboxItem}" DisplayMemberPath="Text" SelectedValuePath="Key" >
 6                     
 7                     
 8                     "Right" Width="240" Orientation="Horizontal" DataContext="{Binding CombboxItem}" >
 9                         "{Binding Key,StringFormat='结果:\{0\}'}" Margin="0,0,15,0" >
10                         "{Binding Text}">
11                     
12                     
13                     
14             

 Model代码:

 1   public class ComplexInfoModel:ObservableObject
 2     {
 3         private String key;
 4         /// 
 5         /// Key值
 6         /// 
 7         public String Key
 8         {
 9             get { return key; }
10             set { key = value; RaisePropertyChanged(()=>Key); }
11         }
12 
13         private String text;
14         /// 
15         /// Text值
16         /// 
17         public String Text
18         {
19             get { return text; }
20             set { text = value; RaisePropertyChanged(()=>Text); }
21         }
22     }

 ViewModel代码:

 1         #region 下拉框相关
 2         private ComplexInfoModel combboxItem;
 3         /// 
 4         /// 下拉框选中信息
 5         /// 
 6         public ComplexInfoModel CombboxItem
 7         {
 8             get { return combboxItem; }
 9             set { combboxItem = value; RaisePropertyChanged(() => CombboxItem); }
10         }
11 
12 
13         private List combboxList;
14         /// 
15         /// 下拉框列表
16         /// 
17         public List CombboxList
18         {
19             get { return combboxList; }
20             set { combboxList = value; RaisePropertyChanged(()=>CombboxList); }
21         }
22         #endregion

说明:CombboxItem是一个全局的属性,作用在当前页面的数据上下文中,结果显示的内容指向下拉框中的选中值,达到共用一个数据的目的。 

这边有四个地方需要注意的:ItemsSource:数据源;SelectedItem:选中的项;DisplayMemberPath:绑定时显示的所属值;SelectedValuePath :绑定时候key的所属值。 

结果:

利刃 MVVMLight 4:绑定和绑定的各种使用场景_第1张图片

  

2、单选框

 1             "10,0,0,50">
 2                 "单选框" FontWeight="Bold" FontSize="12" Margin="0,5,0,5" >
 3                 "RadioButton" >
 4                     "Left" Width="240">
 5                         "{Binding SingleRadio}" IsChecked="{Binding IsSingleRadioCheck}" HorizontalAlignment="Right" Width="240" >
 6                         
 7                     
 8                     "Right" Width="240" Orientation="Horizontal">
 9                         Text="{Binding IsSingleRadioCheck,StringFormat='结果:\{0\}'}" >
10                     
11                 
12             

说明:注意这边使用到了两个属性: SingleRadio,IsSingleRadioCheck,一个用于显示单选框内容,一个用于表示是否选中

结果:

 

3、组合单选框

我们一般会用单选框做组合表示唯一选项,比如性别包含男女,但是只能选择一个。而更多的场景是包含多个选项,但是只能单选的,这时候就需要做单选框组。
 1             "10,0,0,50">
 2                 "组合单选框" FontWeight="Bold" FontSize="12" Margin="0,5,0,5">
 3                 "GroupRadioButton" >
 4                     "Left" Width="240">
 5                         ItemsSource="{Binding RadioButtons}">
 6                             
 7                                 
 8                                     "{Binding Content}" IsChecked="{Binding IsCheck}" GroupName="RadioButtons"
 9                                                  Command="{Binding DataContext.RadioCheckCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}}">  
10                                                                         
11                                 
12                             
13                         
14                     
15 
16                     "Right" Width="240" Orientation="Horizontal">
17                         "{Binding RadioButton.Content,StringFormat='结果:\{0\}'}" >
18                     
19                 
20             

这边使用了ItemsControl,可以根据模板来定义内容,我们在模板中放置我们需要用到的内容。这边需要注意的是:GroupName用一样的,来代表这是一个单选控件组合。

这边有是三个属性进行绑定相关:
RadioButtons:单选框列表数据(循环绑定);Content:单选框显示的内容;IsCheck:单选框的是否选中。  

结果:

利刃 MVVMLight 4:绑定和绑定的各种使用场景_第2张图片

 

4、复选框,复选框与单选框的使用情况类似:

 1   "10,0,0,50">
 2                 "复合框" FontWeight="Bold" FontSize="12" Margin="0,5,0,5" >
 3                 "GroupCheckButton" >
 4                     "Left" Width="240">
 5                         "{Binding CheckButtons}" x:Name="cbt" >
 6                             
 7                                 
 8                                     "{Binding Content}" IsChecked="{Binding IsCheck}"
 9                                                  Command="{Binding DataContext.CheckCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}}"/>
10                                 
11                             
12                         
13                     
14 
15                     "Right" Width="240" Orientation="Horizontal">
16                         "{Binding CheckInfo,StringFormat='结果:\{0\}'}" >
17                     
18                 
19               

 结果:

利刃 MVVMLight 4:绑定和绑定的各种使用场景_第3张图片

 

5、树形控件

View代码:

 1   "10,0,0,50">
 2                 "" FontWeight="Bold" FontSize="12" Margin="0,5,0,5" >
 3                 "TreeButton" >
 4                     "Left" Width="240">
 5                             ItemsSource="{Binding TreeInfo}" x:Name="tree" BorderThickness="0">
 6                             
 7                                 ItemsSource="{Binding Children}">
 8                                     Text="{Binding NodeName}"/>
 9                                 
10                             
11                         
12                     
13                     
14                     "Right" Width="240" Orientation="Horizontal" DataContext="{Binding SelectedItem,ElementName=tree}">
15                             "结果:"/>
16                         Text="{Binding NodeID,StringFormat='NodeID:\{0\}'}"  Margin="0,0,20,0"  />
17                         Text="{Binding NodeName,StringFormat='NodeName:\{0\}'}"/>
18                                         
19                 
20  

Model代码

1  public class TreeNodeModel : ObservableObject
2     {
3         public string NodeID { get; set; }
4         public string NodeName { get; set; }
5         public List Children { get; set; }
6     }

ViewModel代码

 1   #region 树控件
 2 
 3         private List treeInfo;
 4         /// 
 5         /// 树控件数据信息
 6         /// 
 7         public List TreeInfo
 8         {
 9             get { return treeInfo; }
10             set { treeInfo = value; RaisePropertyChanged(()=>TreeInfo); }
11         }
12 
13 
14   #endregion

 结果:

利刃 MVVMLight 4:绑定和绑定的各种使用场景_第4张图片

 

6、ListBox

当我们需要用到循环的列表内容,并且模板化程度高的时候,建议使用ListBox来做绑定。
View代码:
 1             "10,0,0,50" Orientation="Vertical" >
 2                 "ListBox模板" FontWeight="Bold" FontSize="12" Margin="0,5,0,5" >
 3                     
 4                         "Left" DockPanel.Dock="Left" >
 5                             "lb" ItemsSource="{Binding ListBoxData}" Width="500" BorderThickness="0" >
 6                                 
 7                                     
 8                                         
 9                                     
10                                 
11 
12                                 
13                                     
14                                         
15                                             
16                                             
17                                         
18                                     
19                                 
20                             
21                         
22 
23                         "Right" DataContext="{Binding SelectedItem,ElementName=lb}" Margin="15" Orientation="Vertical" >
24                             "{Binding Info,StringFormat='选中:\{0\}'}" >
25                         
26                     
27                 

ViewModel代码:

 1         #region ListBox 模板
 2 
 3         private IEnumerable listBoxData;
 4         /// 
 5         /// LisBox数据模板
 6         /// 
 7         public IEnumerable ListBoxData
 8         {
 9             get { return listBoxData; }
10             set { listBoxData = value;RaisePropertyChanged(()=>ListBoxData); }
11         }
12 
13         #endregion

初始数据:

 1    private void InitListBoxList()
 2         {
 3             ListBoxData = new ObservableCollection<dynamic>(){
 4               new { Img="/MVVMLightDemo;component/Images/1.jpg",Info="樱桃" },
 5               new { Img="/MVVMLightDemo;component/Images/2.jpg",Info="葡萄" },
 6               new { Img="/MVVMLightDemo;component/Images/3.jpg",Info="苹果" },
 7               new { Img="/MVVMLightDemo;component/Images/4.jpg",Info="猕猴桃" },
 8               new { Img="/MVVMLightDemo;component/Images/5.jpg",Info="柠檬" },
 9            };
10         }

 结果:

 利刃 MVVMLight 4:绑定和绑定的各种使用场景_第5张图片

 

 

7、用户控件的集合绑定:

ListBox的列表绑定远远不能满足我们实际工作中的需求,
出于对灵活性、复用性以及代码精简的考虑,需要保证循环列表中的单个元素是独立的元素片段,类似Web中的局部视图。 这时候,使用用户控件会好很多。
 
我们先写一个用户控件,分别设置了他的样式和绑定的属性值,如下:
 1 "MVVMLightDemo.Content.FruitInfoView"
 2              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
 5              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
 6              mc:Ignorable="d" 
 7              d:DesignHeight="300" d:DesignWidth="300">
 8     
 9         
10             
22         
23         
24         
25         "Vertical" Margin="10">
26             
27             
28         
29         
30     
31 

 在目标视图页面注册并使用:

1 xmlns:Content="clr-namespace:MVVMLightDemo.Content" 
 1  "10,0,0,50" Orientation="Vertical" >
 2                     "用户控件模板列表" FontWeight="Bold" FontSize="12" Margin="0,5,0,5" >
 3                     "Left" Width="500" >
 4                          "{Binding FiList}" HorizontalAlignment="Left" >
 5                             
 6                                 
 7                                     
 8                                                        
 9                             
10                              
11                             
12                             
13                                 
14                                     
15                                     
16                                 
17                             
18                              
19                         
20                         
21                     
22  

  结果:

利刃 MVVMLight 4:绑定和绑定的各种使用场景_第6张图片

 

后记:这篇更确切的说是绑定的相关知识,只是应用了MVVM模式来实现。

工作太忙了,写的太慢,其实后面几篇都已经成稿了,一直放在Note里面等待认真检查,品质太差怕误导其他开发人员。

 

点击下载代码

 

转载请标明出处,谢谢

 

转载于:https://www.cnblogs.com/wzh2010/p/6425060.html

你可能感兴趣的:(利刃 MVVMLight 4:绑定和绑定的各种使用场景)