[WPF系列]-DataBinding(数据绑定) 自定义Binding
自定义Binding
A base class for custom WPF binding markup extensions
BindingDecoratorBase
Code:
public class LookupExtension : BindingDecoratorBase {//A property that can be set in XAMLpublic string LookupKey { get; set; }public override object ProvideValue(IServiceProvider provider){//delegate binding creation etc. to the base classobject val = base.ProvideValue(provider);//try to get bound items for our custom work DependencyObject targetObject;DependencyProperty targetProperty;bool status = TryGetTargetItems(provider, out targetObject,out targetProperty);if (status){//associate an input listener with the control InputHandler.RegisterHandler(targetObject, LookupKey);}return val;} }
XAML:
<TextBox Name="txtZipCode"><TextBox.Text><local:LookupExtension Source="{StaticResource MyAddress}"Path="ZipCode"LookupKey="F5" /></TextBox.Text> </TextBox>
效果图:
---------------------------------------------===================================------------------------------
DelayBinding: a custom WPF Binding
<TextBox Text="{z:DelayBinding Path=SearchText, Delay='00:00:01'}" />
[MarkupExtensionReturnType(typeof(object))] public class DelayBindingExtension : MarkupExtension {public DelayBindingExtension(){Delay = TimeSpan.FromSeconds(0.5);}public DelayBindingExtension(PropertyPath path) : this(){Path = path;}public IValueConverter Converter { get; set; }public object ConverterParamter { get; set; }public string ElementName { get; set; }public RelativeSource RelativeSource { get; set; }public object Source { get; set; }public bool ValidatesOnDataErrors { get; set; }public bool ValidatesOnExceptions { get; set; }public TimeSpan Delay { get; set; }[ConstructorArgument("path")]public PropertyPath Path { get; set; }[TypeConverter(typeof(CultureInfoIetfLanguageTagConverter))]public CultureInfo ConverterCulture { get; set; }public override object ProvideValue(IServiceProvider serviceProvider){var valueProvider = serviceProvider.GetService(typeof (IProvideValueTarget)) as IProvideValueTarget;if (valueProvider != null){var bindingTarget = valueProvider.TargetObject as DependencyObject;var bindingProperty = valueProvider.TargetProperty as DependencyProperty;if (bindingProperty == null || bindingTarget == null){throw new NotSupportedException(string.Format("The property '{0}' on target '{1}' is not valid for a DelayBinding. The DelayBinding target must be a DependencyObject, "+ "and the target property must be a DependencyProperty.", valueProvider.TargetProperty, valueProvider.TargetObject));}var binding = new Binding();binding.Path = Path;binding.Converter = Converter;binding.ConverterCulture = ConverterCulture;binding.ConverterParameter = ConverterParamter;if (ElementName != null) binding.ElementName = ElementName;if (RelativeSource != null) binding.RelativeSource = RelativeSource;if (Source != null) binding.Source = Source;binding.ValidatesOnDataErrors = ValidatesOnDataErrors;binding.ValidatesOnExceptions = ValidatesOnExceptions;return DelayBinding.SetBinding(bindingTarget, bindingProperty, Delay, binding);}return null;} }
public class DelayBinding {private readonly BindingExpressionBase _bindingExpression;private readonly DispatcherTimer _timer;protected DelayBinding(BindingExpressionBase bindingExpression, DependencyObject bindingTarget, DependencyProperty bindingTargetProperty, TimeSpan delay){_bindingExpression = bindingExpression;// Subscribe to notifications for when the target property changes. This event handler will be // invoked when the user types, clicks, or anything else which changes the target propertyvar descriptor = DependencyPropertyDescriptor.FromProperty(bindingTargetProperty, bindingTarget.GetType());descriptor.AddValueChanged(bindingTarget, BindingTarget_TargetPropertyChanged);// Add support so that the Enter key causes an immediate commitvar frameworkElement = bindingTarget as FrameworkElement;if (frameworkElement != null){frameworkElement.KeyUp += BindingTarget_KeyUp;}// Setup the timer, but it won't be started until changes are detected_timer = new DispatcherTimer();_timer.Tick += Timer_Tick;_timer.Interval = delay;}private void BindingTarget_KeyUp(object sender, KeyEventArgs e){if (e.Key != Key.Enter) return;_timer.Stop();_bindingExpression.UpdateSource();}private void BindingTarget_TargetPropertyChanged(object sender, EventArgs e){_timer.Stop();_timer.Start();}private void Timer_Tick(object sender, EventArgs e){_timer.Stop();_bindingExpression.UpdateSource();}public static object SetBinding(DependencyObject bindingTarget, DependencyProperty bindingTargetProperty, TimeSpan delay, Binding binding){// Override some specific settings to enable the behavior of delay bindingbinding.Mode = BindingMode.TwoWay;binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;// Apply and evaluate the bindingvar bindingExpression = BindingOperations.SetBinding(bindingTarget, bindingTargetProperty, binding);// Setup the delay timer around the binding. This object will live as long as the target element lives, since it subscribes to the changing event, // and will be garbage collected as soon as the element isn't required (e.g., when it's Window closes) and the timer has stopped.new DelayBinding(bindingExpression, bindingTarget, bindingTargetProperty, delay);// Return the current value of the binding (since it will have been evaluated because of the binding above)return bindingTarget.GetValue(bindingTargetProperty);} }
参考
Automatically validating business entities in WPF using custom binding and attributes
Flexible and Powerful Data Binding with WPF, Part 2
转载于:https://www.cnblogs.com/HQFZ/p/4143149.html
[WPF系列]-DataBinding(数据绑定) 自定义Binding相关推荐
- WPF中的数据绑定Data Binding使用小结
完整的数据绑定的语法说明可以在这里查看: http://www.nbdtech.com/Free/WpfBinding.pdf MSDN资料: Data Binding: Part 1 http:// ...
- WPF入门教程系列十五——WPF中的数据绑定(一)
使用Windows Presentation Foundation (WPF) 可以很方便的设计出强大的用户界面,同时 WPF提供了数据绑定功能.WPF的数据绑定跟Winform与ASP.NET中的数 ...
- 数据绑定(Binding)
Windows Presentation Foundation (WPF) 中的数据绑定为应用程序提供了一种简单.一致的数据表示和交互方法.元素能够以公共语言运行时 (CLR) 对象和 XML 形式绑 ...
- Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定)
原文:Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定) ------------------------------ ...
- 【翻译】WPF中的数据绑定表达式
有很多文章讨论绑定的概念,并讲解如何使用StaticResources和DynamicResources绑定属性.这些概念使用WPF提供的数据绑定表达式.在本文中,让我们研究WPF提供的不同类型的数据 ...
- WPF学习笔记(数据绑定篇3)
接上回的<WPF学习笔记(数据绑定篇2)>,继续 BindValidation 此示例演示了: 如何使用错误模板: 使用样式显示错误信息: 如何在校验发生异常时执行回调: 首先,你可以看见 ...
- DataBinding → 数据绑定 (使用篇)
/ 今日科技快讯 / 华为近日发布2022年第一季度经营业绩,实现销售收入1310亿元人民币,同比下降13.9%.华为第一季度净利润率同比下降6.8个百分点,至4.3%.华为轮值董事长胡厚崑表 ...
- WPF入门:数据绑定
原文:WPF入门:数据绑定 上一篇我们将XAML大概做了个了解 ,这篇将继续学习WPF数据绑定的相关内容 数据源与控件的Binding Binding作为数据传送UI的通道,通过INotityProp ...
- 【值转换器】 WPF中Image数据绑定Icon对象
原文:[值转换器] WPF中Image数据绑定Icon对象 这是原来的代码: <Image Source="{Binding MenuIcon}" /> 这里的Men ...
- WPF使用DataGrid数据绑定
文章目录 前言 一.新建数据模型 二.界面设计 三.数据初始化 四.WPF DataGrid.DataGridComboBoxColumn 数据绑定 前言 一.新建数据模型 public class ...
最新文章
- oracle分页包,Oracle分页获取数据的实现 (包和存储过程)
- jmp、JE、JZ、JNE、JNT指令
- leetcode 978. 最长湍流子数组(滑动窗口)
- 公共技术点之 Java 注解 Annotation
- (ZZ)A*算法入门
- Wireshark-002导入导出
- 橙子减肥法:好吃快速成为瘦美人 - 健康程序员,至尚生活!
- 设计模式之GOF23解释器模式
- Linux下udev详细介绍
- matlab信号建模,Matlab在信号处理中的建模仿真
- springmuvc如何设置jsp的input跳转_小程序有链接吗?如何获取小程序的链接?
- FPGA杂记5——格雷码转换设计
- OpenGL第三方库:glad初始了解与下载
- 联创宽带上网助手协议的简单分析(一)start包和off包
- ArcMap符号样式制作
- 如何解决百度云下载大文件限速问题
- BatchNorm和LayerNorm的区别
- LabVIEW基础(1)
- android sqlite fts4,SQLite FTS3/FTS4与一些使用心得
- 读书笔记--项亮《推荐系统实践》第五章
热门文章
- thinkphp 接收小程序json数组
- Spring框架工作原理
- rsa算法的java实现,RSA算法的实现——java版
- 中blur函数_实时渲染中的软阴影技术
- DEDECMS v5.7 实现导航条下拉二级菜单
- java中几种Map在什么情况下使用,并简单介绍原因及原理
- 阶段2 JavaWeb+黑马旅游网_15-Maven基础_第1节 基本概念_03maven一键构建概念
- [Algorithm] Fibonacci Sequence - Anatomy of recursion and space complexity analysis
- nodejs语法问题
- bzoj 2212 Tree Rotations