微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Silverlight数据绑定/IValueConverter


先回忆一下aspx中的处理:

在aspx中,可以直接在后台定义一个变量,然后前台就可以用<%=xxx%>来将其"绑定"html控件上,比如下面这样,实在是很方便:

代码
using  System;

namespace  WebApplication1
{
    
public   partial class  _Default : System.Web.UI.Page
    {
        
protected   string  _Test  =  DateTime.Now.ToString();

        
void  Page_Load( object  sender, EventArgs e)
        {

        }
    }
}

 

代码
<% @ Page Language = " C# "  AutoEventWireup true  CodeBehind Default.aspx.cs  Inherits WebApplication1._Default %>

<! DOCTYPE html PUBLIC  -//W3C//DTD XHTML 1.0 Transitional//EN   http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd > < html xmlns http://www.w3.org/1999/xhtml
head runat server
    
title ></ </ head body form id form1  runat input id Text1  type text value = " <%=_Test %> /> form html >

 

但到了Silverlight中,要想直接将后台的变量绑定到某个控件上却是行不通的,通常我们得先定义一个类,然后在类里定义属性,才能把类实例属性绑定到控件:

简单绑定: 

代码
 System;
 System.Windows;
 System.Windows.Controls;
 System.Windows.Data;
 System.Windows.Shapes;

 BindVariable
{
    
 MainPage : UserControl
    {

        
 MyClass {  string  Test {  set get ; } }       

        
 MyClass TestClass;
     
        
 MainPage()
        {           
            InitializeComponent();           
            TestClass 
= new  MyClass();
            TestClass.Test 
123 ;
            
this .textBox1.DataContext   TestClass;           
        }
      
    }   
}

 

     < StackPanel >         
      
TextBox  x:Name ="textBox1"   Text =" {Binding Test} " />   
    
</ >

 

这样就完成了功能最简单的绑定,还想玩得更深入一点,比如实现OneWay,TwoWay方式的绑定(不清楚绑定模式的朋友,建议先参看http://www.cnblogs.com/yjmyzz/archive/2009/11/09/1599058.html),这样仍然不行,比如我们稍微把刚才的代码改一下:

"自动更新"的绑定: 

代码
< UserControl
    
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d
="http://schemas.microsoft.com/expression/blend/2008"  xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class
="BindVariable.MainPage"
   
>    
    
    
StackPanel  Orientation ="Vertical"         
      
TextBox  x:Name ="textBox1"  Text =" {Binding Test} " />   
      
Button  ="btnChange"  Content ="Change Test"  Click ="btnChange_Click" ></ Button </ StackPanel UserControl >

 

代码
;
            
this .textBox1.DataContext   TestClass;          
        }

    
private  btnChange_Click( ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, RoutedEventArgs e)
        {
            
.TestClass.Test  456 ;
        }
      
    }   
}

运行后,点击按钮,发现textBox1中的内容并无变化,原因是:要想实现源与目标的数据自动关联更新,MyClass得实现INotifyPropertyChanged接口,我们把MyClass的定义改成下面这样: 

代码
 MyClass:INotifyPropertyChanged {
    
event  PropertyChangedEventHandler PropertyChanged;

    
 _test;

    
 Test 
    { 
        
{
        _test 
 value;
        
if  (PropertyChanged  != null
        {
            PropertyChanged(
 PropertyChangedEventArgs( Test ));
        }
    }
        
 {  return  _test; }
    } 
}

再次运行,发现点击按钮后,textBox1的内容变成了456,达到预期的效果了.
绑定集合(数据集):

很多应用场合中,数据来源不仅只有一个实例(或一条记录)--比如从数据库中检索的记录,这时如果想绑定数据并实现自动更新,应使用集合绑定(类似于aspx中的DataSet或DataTable)。要注意的是,使用集合绑定并实现自动更新,除了要实现 INotifyPropertyChanged 外,还要实现 INotifyCollectionChanged。幸好.net框架已经有一个ObservableCollection<T> 类,该类具有 INotifyCollectionChanged 和 INotifyPropertyChanged 的内置实现。可以直接拿来用:

代码

    xmlns:local
="clr-namespace:BindVariable"        
        
ListBox  ="lst"
            
ListBox.ItemTemplate
                
DataTemplate
                    

                        
TextBlock  Text TextBlock
        
ListBox

代码
 System.Collections.ObjectModel;
 System.Windows.Controls;

; } }        

        ObservableCollection
MyClass  oc   ObservableCollection (){
            
 MyClass() { Test  1  },
            
2 3  }
        };
     
        
 MainPage()
        {           
            InitializeComponent();
            
.lst.ItemsSource   oc;
        }

        
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, RoutedEventArgs e)
        {
            oc.Add(
4  });
        }      
    }
}

IValueConverter:

上述的绑定,都是将数据原封不动的绑定并显示,如果我们希望在绑定时,能对数据的输出做一些变化,比如:代表性别的"1,0"输出时希望变成"男,女",该怎么办呢?(silverlight中可不允许象aspx那样用<%# Eval("Sex").ToString()=="1"?"男":"女"%>来搞定)  答案:IValueConverter 

代码
 System.Windows.Data;

 MyClass
        {
            
; }
            
bool  Sex {  ; }
        }

        ObservableCollection
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0,Sex true false  }
        };

        
 MainPage()
        {
            InitializeComponent();
            
ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, Sex   });
        }

    }

    
/// <summary>
    
 bool转化为性别字符串
    
</summary>
     class  BoolToSexConverter : IValueConverter
    {

        
object  Convert(  value, Type targettype  parameter, System.Globalization.CultureInfo culture)
        {
            
try
            {
                
return  (( bool )value)  ?   "  :  ;
            }
            
catch ?             }

        }


        
// 只有TwoWay模式下,才需要实现该方法,否则可以不用理           ConvertBack( throw new  NotImplementedException();
        }
    }
}

 

代码
  
        
StackPanel.Resources local:BoolToSexConverter  x:Key ="Bool2Sex" local:BoolToSexConverter ="Horizontal" ="," {Binding Path=Sex,  Converter={StaticResource Bool2Sex}} >

也许您注意到了IValueConverter的Convert方法中,还能传入参数!我们可以利用这个玩点小花样,比如界面上有三个矩形,其中"矩形2的宽度"等于"矩形1的宽度"+"一个任意指定的固定值",矩形3的宽度矩形1与矩形2的宽度总和,不允用 rect2.width = rect1.width,rect3.width = rect2.width + rect1.width 来处理:) 您会怎么做呢? 

代码
 MainPage : UserControl
    {       
        
 MainPage()
        {
            InitializeComponent();            
        }
    }

    
 DoubleAddConverter : IValueConverter
    {

        
 Convert( ottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; font-family:'Courier New'; font-size:12px; line-height:1.5; color:rgb(0, System.Globalization.CultureInfo culture)
        {
            

            {
                
double .Parse(value.ToString())  + .Parse(parameter.ToString());
            }
            
50.0 ;
            }

        }


        
//           ConvertBack(  NotImplementedException();
        }
    }


    
 FrameworkElementAddConverter : IValueConverter
    {

        
 ((App.Current.RootVisual  as  FrameworkElement).FindName(parameter.ToString())   FrameworkElement).Width;
            }
            
 NotImplementedException();
        }
    }
    
}

 

 

代码
="Vertical"  HorizontalAlignment ="Left"          
        
local:DoubleAddConverter  ="DoubleAdd" local:DoubleAddConverter local:FrameworkElementAddConverter  ="FEAdd" local:FrameworkElementAddConverter
        
        
Rectangle  ="rect1"  Width ="100"  Height ="50"  Fill ="Gray" ="Left" Rectangle ="rect2" {Binding Width, Converter={StaticResource DoubleAdd}, ConverterParameter=100, ElementName=rect1, Mode=OneWay} "   Fill ="Red" ="rect3" ="Blue" >

 

这样就搞定了,也许有人会问:为啥不用  rect2.width = rect1.width,rect3.width = rect2.width + rect1.width 呢?不是更简单吗?

存在即合理,这样的好处是不必用硬编码把逻辑写死,我们可以把常用的转换处理抽象出来,比如封装成一个单纯的dll程序集,以后需要用到的地方,直接引用就可以了,能有效的重用代码

 

转载请注明来自菩提树下的杨过http://www.cnblogs.com/yjmyzz/archive/2009/12/07/silverlight-binding.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐