Binding上
来源:互联网 发布:生成艺术字软件 编辑:程序博客网 时间:2024/05/02 04:42
1. 绑定概述
- 数据绑定(data binding)是将控件和element链接到数据的技术。它常常可以取代事件处理函数,大大简化代码。
- 数据绑定具有源(source)和目标(target),一般来说,源是某种数据,目标则是一个控件。(有时候角色会对调)
- “绑定”一定是在target上做设定
- 绑定的目标必须继承自DependcyObject,绑定所设定的property必须有dependency property的支持
2. 简单实例
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- Binding Source. --> <ScrollBar Name="scroll" Orientation="Horizontal" Margin="24" Maximum="100" LargeChange="10" SmallChange="1" /> <!-- Binding Target. --> <Label HorizontalAlignment="Center" Content="{Binding ElementName=scroll, Path=Value}" /></StackPanel>
代码说明:
- label的content将会实时显示Scrollbar的Value值的变化
- 要注意语法,如果不习惯用大括号,还可以这么写<Label.Content> <Binding ElementName="scroll" Path="Value" /></Label.Content>
c#代码设定:
其中SetBinding方法第一个参数必须为Denpendcy PropertyBinding bind = new Binding();bind.Source = scroll;bind.Path = new PropertyPath(ScrollBar.ValueProperty);lbl.SetBinding(Label.Content, bind);
3. 绑定的4种模式
- Mode=“OneWay”
源到目标的绑定 - Mode=“TwoWay”
双向的绑定 - Mode=“OneTime”
一次绑定,它从目标源取的数据,进行初始化,但不会持续跟踪变化 - Mode=“OneWayToSource”
目标到源的绑定,即“源根据目标来更新”。当目标的property没有denpendcy property支持,而源的property有denpendcy property支持时,可以将绑定放在源上,然后设置为该绑定模式。
注:默认的绑定模式是不确定的,所以最好显示地指定绑定模式
4. 通过DataContext属性绑定
DataContext可以沿着element tree中被继承,所以如果你为一个element设定DataContext,则该element所有的孩子都会受到影响,例如:
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding ElementName=scroll}"> <!-- Binding Source. --> <ScrollBar Name="scroll" Orientation="Horizontal" Margin="24" Minimum="1" Maximum="100" LargeChange="10" SmallChange="1" /> <!-- Binding Targets. --> <Label HorizontalAlignment="Center" Content="{Binding Path=Value, Mode=OneWay}" /> <Button HorizontalAlignment="Center" Margin="24" FontSize="{Binding Path=Value, Mode=OneWay}"> Bound Button </Button></StackPanel>
如果在一个面板内,许多控件都绑定到一个特定对象的不同property上,只要将DataContext设定到该类型的不同对象上,所以的控件都会反应此新对象的内容。
5. Converter
当数据传递时,可能需要转换数据,Binding类包括了一个Coverter的property,该属性的对象类型必须实现接口:IvalueConverter
格式如下:
public class MyConverter : IValueConverter { /// <summary> /// 源到目标的转换 /// </summary> /// <param name="value">绑定源生成的值</param> /// <param name="typeTarget">绑定目标属性的类型,也就是该方法的返回类型</param> /// <param name="param">要使用的转换器参数(附加参数,可以是任何数据类型或者对象引用)</param> /// <param name="culture">要用在转换器中的区域性(一般可以忽略)</param> public object Convert(object value, Type typeTarget, object param, CultureInfo culture) { //... } /// <summary> /// 目标到源的转换 /// </summary> /// <param name="value">绑定目标生成的值</param> /// <param name="typeTarget">要转换到的类型,也就是该方法的返回类型</param> /// <param name="param">要使用的转换器参数</param> /// <param name="culture">要用在转换器中的区域性</param> public object ConvertBack(object value, Type typeTarget, object param, CultureInfo culture) { //... } }
在c#中使用以上定义的Converter:
Binding bind = new Binding();bind.Converter = new MyConverter();
在XAML中使用以上定义的Converter,需要先将其加到Resource中,在Resources section中:
<src:MyConverter x:Key="conv" />
然后使用:
"{Binding ... Convert={StaticResource conv}, ... }"
6. 一个使用Converter的数据绑定完整实例
在c#代码中定义Converter,将数据在double和decimal中转换
using System;using System.Globalization;using System.Windows;using System.Windows.Data;namespace Petzold.DecimalScrollBar{ [ValueConversion(typeof(double), typeof(decimal))] public class DoubleToDecimalConverter : IValueConverter { public object Convert(object value, Type typeTarget, object param, CultureInfo culture) { decimal num = new Decimal((double)value); if (param != null) num = Decimal.Round(num, Int32.Parse(param as string)); return num; } public object ConvertBack(object value, Type typeTarget, object param, CultureInfo culture) { return Decimal.ToDouble((decimal)value); } }}
代码说明:
- MSDN建议在定义Converter之前使用ValueConversion(ValueConversionAttribute类) attribute,指定转换器的实现中涉及的数据类型。
- 注意上面用到了附加参数param,用来控制小数点位数。
在XAML文件中使用数据绑定:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:Petzold.DecimalScrollBar" Title="Decimal ScrollBar"> <Window.Resources> <src:DoubleToDecimalConverter x:Key="conv" /> </Window.Resources> <StackPanel> <!-- Binding Source. --> <ScrollBar Name="scroll" Orientation="Horizontal" Margin="24" Maximum="100" LargeChange="10" SmallChange="1" /> <!-- Binding Target. --> <Label HorizontalAlignment="Center" Content="{Binding ElementName=scroll, Path=Value, Converter={StaticResource conv}, ConverterParameter=2}" /> </StackPanel></Window>
代码说明:
- 注意引用命名空间
- 通过设置ConverterParameter property,指定保留两位小数。
- 当移动滚动条时,label会显示两位小数的Value值
7. 多重绑定(multi-binding)
- 多重绑定将来自多个源的多个对象,合并为一个单一的目标。
- 多重绑定的转换器必须实现IMultiValueConverter接口
实现IMultiValueConverter接口的例子
public class RgbToColorConverter : IMultiValueConverter { public object Convert(object[] value, Type typeTarget, object param, CultureInfo culture) { Color clr = Color.FromRgb((byte)(double)value[0], (byte)(double)value[1], (byte)(double)value[2]); if (typeTarget == typeof(Color)) return clr; if (typeTarget == typeof(Brush)) return new SolidColorBrush(clr); return null; } public object[] ConvertBack(object value, Type[] typeTarget, object param, CultureInfo culture) { Color clr; object[] primaries = new object[3]; if (value is Color) clr = (Color)value; else if (value is SolidColorBrush) clr = (value as SolidColorBrush).Color; else return null; primaries[0] = clr.R; primaries[1] = clr.G; primaries[2] = clr.B; return primaries; } }
代码说明:
- 该转换器将三个double值转换成color或者Brush
- 注意Convert的第一个参数是对象数组
使用该转换器:
<Border.Background> <MultiBinding Converter="{StaticResource convRgbToColor}"> <Binding ElementName="scrRed" Path="Value" Mode="OneWay "/> <Binding ElementName="scrGreen" Path="Value" Mode="OneWay "/> <Binding ElementName="scrBlue" Path="Value" Mode="OneWay "/> </MultiBinding> </Border.Background>
代码说明:
- 该Binding从三个ScrollBar(scrRed,scrGreen,scrBlue)中获取value值,然后传递到转换器的对象数组
- 转换器根据这个三个值返回一个Brush,设置为Border的Background属性值
- 对于MultiBinding的Binding element,也可以使用各自的转换器
8. UpdateSourceTrigger属性
- Binding的UpdateSourceTrigger属性用来设定更新绑定源的时间(在TwoWay或OneWayTOSource模式下使用)
- UpdateSourceTrigger的值为枚举类型
- LostFocus:当控件失去焦点时更新源(在数据源是数据库的情况下,可以避免频繁操作数据库)
- PropertyChanged: 当绑定的目标属性的值发生改变时更新源,这样可以实时反应目标属性的变化
- Explicit:仅在调用 UpdateSource 方法时更新绑定源
如果选用此选项,需要先在“定义此binding的element(注:按我的理解就是目标控件了)”上调用GetBindingExpression方法
// itemNameTextBox is an instance of a TextBoxBindingExpression be = itemNameTextBox.GetBindingExpression(TextBox.TextProperty);
然后在点击“更新”或“确定”按钮时,调用UpdateSource方法:
be.UpdateSource();
0 0
- Binding上
- Binding
- binding
- Binding
- Binding
- Flex Data Binding详解(上)
- WPF 值绑定binding (上)
- 深入浅出WPF(7)——数据的绿色通道,Binding(上)
- 深入浅出WPF(7)——数据的绿色通道,Binding(上)
- 深入浅出WPF(7)——数据的绿色通道,Binding(上)
- Data Binding Guide——google官方文档翻译(上)
- 深入浅出WPF(7)——数据的绿色通道,Binding(上)
- mac 编程上遇到dyld: lazy symbol binding failed: Symbol not found的解决方案
- Array Binding
- SyncML binding
- Interrupt Binding
- WPF binding
- WPF BINDING
- Lua解析Html简单示例。
- Oracle 还原历史统计信息
- camera摄像原理之三:色温和自动白平衡
- "name.bat" is not a recognized as an internal or external command,operable program or batch file
- samba的一些小结
- Binding上
- Test
- 测试JSTL表达式 .
- Redis安装整理(window平台) +php扩展redis
- C语言 ## __VA_ARGS__ 宏
- 三、图的建立及遍历
- DSP学习步骤
- Ubuntu查看ssh服务是否开启
- node.js xmpp