WPF 基础入门 (Binding 一)

1 通知机制

    WPF 中Binding可以比作数据的桥梁,桥梁的两端分别是Binding的源(Source)和目标(Target)。一般情况下,Binding源是逻辑层对象,Binding目标是UI层的控件对象,这样,数据就会通过Binding送达UI层,被UI层展现。后台数据变更后,如何通知到UI层,并更新显示,则通过INotifyPropertyChanged接口实现。

public class BaseNotifyProperty:INotifyPropertyChanged
{
	public event PropertyChangedEventHandler PropertyChanged;
	public void OnPropertyChanged(string propertyName="")
	{
		if (PropertyChanged != null)
			PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
	}
}

public string DirFullName
{
   get { return m_DirFullName; }
   set { m_DirFullName = value; OnPropertyChanged("DirFullName"); }
}

2 Binding实现

2.1 绑定(Binding)

    现在我有一个Slider和一个Textbox。我希望在滑动Slider的时候,Textbox实时显示Slider的Value属性的值。该怎么办呢?

    XAML代码如下:


	
	

    与上述等价的C#代码为:

t1.SetBinding(TextBox.TextProperty, new Binding("Value") { ElementName = "s1" });

    还可以这样写:

Binding binding = new Binding();
binding.Path = new PropertyPath("Value");
binding.Source = s1;
t1.SetBinding(TextBox.TextProperty, binding);

2.2  多重绑定(MultiBinding)

    MultiBinding多个数据源进行组合绑定


	
		
			
			
		
	

3 绑定转换器

    在某种使用场景中,需要对Binding的对象进行转换,如Bool转Visibility,DateTime转String等。

WPF提供了两种Converter接口,单值转换的接口IValueConverter和多值转换的接口IMultiValueConverter,它们都属于System.Windows.Data命名空间,在程序集PresentationFramework.dll中。这两种值转换器都是分区域性的。其中方法ConvertConvertBack都具有指示区域性信息的culture参数。如果区域性信息与转换无关,那么在自定义转换器中可以忽略该参数。

public class ProgressValueToAngleConverter : IValueConverter
{
	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
	{
		if (value != null)
		{     
			double prec=(double)value;
			if(prec<0||prec>100)
				prec=0;
			return 3.6 *prec;
		}
		return 0;
	}

}

public class MultiBindingStringFormatConverter:IMultiValueConverter
{
	public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
	{   
		object result = null;
		if (values != null)
		{  
			var item=values.Last();
			if (item != null)
			{
				string str = item.ToString();
				result = (object)System.String.Format(str, values);
			}
			else
			{
				result = values[0].ToString();
			}
		 
		}
	  return result;
	}
}

5.4 格式化(StringFormat)

•	货币格式

输出:$123.46
•	货币格式,一位小数

输出: $123.5
•	前文字
 
单价:$123.46
•	后文字
 
输出: 123.45678元
•	固定的位数,位数不能少于未格式化前,仅支持整形
 
输出: 086723
•	指定小数点后的位数
 
输出:28768234.9329
•	用分号隔开的数字,并指定小数点后的位数

输出:28,768,234.933
•	格式化百分比
 
输出: 78.9 %
•	占位符
 
输出: 0123.46
 
输出: 123.46
•	日期/时间
 
输出: 5/4/2015
 
输出: Monday, May 04, 2015
 
输出: Monday, May 04, 2015 5:46 PM

输出: Monday, May 04, 2015 5:46:56 PM

输出: 5/4/2015 5:46 PM

输出: 5/4/2015 5:46:56 PM
 
输出: May 04

输出: May 04
 
输出: 5:46 PM
 
输出: 5:46:56 PM
 
输出: 2015年05月04日
输出: 2015-05-04
 
输出: 2015-05-04 17:46

输出: 2015-05-04 17:46:56
•	多重绑定






输出: 姓名:AAbb

**************************************************************************************************************

你可能感兴趣的:(#,WPF,基础学习,wpf,WPF,基础,Binding)