Jaasdsa

导航

 

得意得意得意看了好多博客,发现很多都不能用,嘿嘿,自己终于实现了;

废话不多说,上代码:

XAML代码如下:

 1 <Window x:Class="WpfApplication7.MainWindow"  
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
 6         xmlns:local="clr-namespace:WpfApplication7"  
 7         mc:Ignorable="d"  
 8         Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">  
 9     <StackPanel >  
10         <Label Name="lbl" Content="{Binding IntValue}" Background="#FFEA7474"></Label>  
11         <Slider Name="sli"  TickFrequency="1" Maximum="100" ValueChanged="sli_ValueChanged"></Slider>  
12     </StackPanel>  
13 </Window>  

Label标签用于显示IntValue 改变后的值,IntValue是Person里面的属性,想要绑定实现,则必须将Person的对象ObjPerson赋值给Label.DataContent

Slider用于通过事件修改IntValue;

CS代码如下:

 1 using System;  
 2 using System.ComponentModel;  
 3 using System.Windows;  
 4 namespace WpfApplication7  
 5 {  
 6   
 7     public partial class MainWindow : Window  
 8     {  
 9         public MainWindow()  
10         {  
11             InitializeComponent();  
12         }  
13         Person objPerson = new Person();//实例化Person  
14         private void Window_Loaded(object sender, RoutedEventArgs e)  
15         {  
16           this.lbl.DataContext = objPerson;//将Person类赋值给Label,否则XAML的绑定将无效,因为Label不知道他绑定的IntValue是谁  
17         }  
18   
19         private void sli_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)  
20         {  
21             objPerson.IntValue =Convert.ToInt32( sli.Value);//此代码表示Slider滑块移动触发ValueChanged事件,并将Value传递给Person.IntValue;  
22         }  
23     }  
24     class Person : INotifyPropertyChanged//要实现绑定到变量,必须实现INotifyPropertyChanged  
25     {  
26         private int intvalue;//私有  
27         public int IntValue  
28         {  
29             get { return intvalue; }//获取值时将私有字段传出;  
30             set { intvalue = value;//赋值时将值传给私有字段  
31                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IntValue"));//一旦执行了赋值操作说明其值被修改了,则立马通过INotifyPropertyChanged接口告诉UI(IntValue)被修改了  
32             }  
33         }  
34         public event PropertyChangedEventHandler PropertyChanged;//必须实现  
35     }  
36 }  

 

posted on 2016-12-12 16:55  Jaasdsa  阅读(449)  评论(0编辑  收藏  举报