[WPF系列]-DataBinding(数据绑定) 自定义Binding

时间:2022-09-05 17:58:52

自定义Binding

A base class for custom WPF binding markup extensions

BindingDecoratorBase

[WPF系列]-DataBinding(数据绑定) 自定义Binding

Code:

public class LookupExtension : BindingDecoratorBase
{
//A property that can be set in XAML
public string LookupKey { get; set; } public override object ProvideValue(IServiceProvider provider)
{
//delegate binding creation etc. to the base class
object 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>

效果图:

[WPF系列]-DataBinding(数据绑定) 自定义Binding

---------------------------------------------===================================------------------------------

DelayBinding: a custom WPF Binding

 

[WPF系列]-DataBinding(数据绑定) 自定义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 property
var descriptor = DependencyPropertyDescriptor.FromProperty(bindingTargetProperty, bindingTarget.GetType());
descriptor.AddValueChanged(bindingTarget, BindingTarget_TargetPropertyChanged); // Add support so that the Enter key causes an immediate commit
var 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 binding
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; // Apply and evaluate the binding
var 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

[WPF系列]-DataBinding(数据绑定) 自定义Binding的更多相关文章

  1. WPF QuickStart系列之数据绑定&lpar;Data Binding&rpar;

    这篇博客将展示WPF DataBinding的内容. 首先看一下WPF Data Binding的概览, Binding Source可以是任意的CLR对象,或者XML文件等,Binding Targ ...

  2. WPF中的数据绑定Data Binding使用小结

    完整的数据绑定的语法说明可以在这里查看: http://www.nbdtech.com/Free/WpfBinding.pdf MSDN资料: Data Binding: Part 1 http:// ...

  3. &lbrack;WPF系列&rsqb;-DataBinding 绑定计算表达式

            Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth, Converter={Stat ...

  4. &lbrack;WPF系列&rsqb;-DataBinding 枚举类型数据源

    public class EnumerationDataProvider : ObjectDataProvider { public Type EnumerationType { get; set; ...

  5. WPF学习09:数据绑定之 Binding to List Data

    从WPF学习03:Element Binding我们可以实现控件属性与控件属性的绑定. 从WPF学习07:MVVM 预备知识之数据绑定 我们可以实现控件属性与自定义对象属性的绑定. 而以上两个功能在实 ...

  6. WPF编游戏系列 之五 数据绑定

    原文:WPF编游戏系列 之五 数据绑定        在上一篇通过用户控件将重复使用的控件封装为一个控件组,大大减少了C#代码数量,本篇继续对该控件组进行数据绑定,节省为每个控件赋值的工作.对于数据绑 ...

  7. WPF入门教程系列十五——WPF中的数据绑定&lpar;一&rpar;

    使用Windows Presentation Foundation (WPF) 可以很方便的设计出强大的用户界面,同时 WPF提供了数据绑定功能.WPF的数据绑定跟Winform与ASP.NET中的数 ...

  8. WPF之数据绑定Data Binding

    一般情况下,应用程序会有三层结构:数据存储层,数据处理层(业务逻辑层),数据展示层(UI界面). WPF是“数据驱动UI”. Binding实现(通过纯C#代码) Binding分为source和ta ...

  9. &lbrack;WPF系列&rsqb;-TreeView的常用事项

    引言 项目经常会用Treeview来组织一些具有层级结构的数据,本节就将项目使用Treeview常见的问题作一个总结. DataBinding数据绑定 DataTemplate自定义 <Hier ...

随机推荐

  1. MySQL点滴

    1. 只安装Server和Workbench即可: 2. 安装时安装Windows服务,可以在“管理 > 服务”中开启关闭服务: 3. mysql -uroot -p1234 4. PHP Fa ...

  2. 使用epel源安装依赖包时报错

    [root@test_web1 ~]#  rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch. ...

  3. sublime text2 中文乱码的解决办法

    1.安装Sublime Package Control 在Sublime Text 2上用Ctrl+-打开控制台并在里面输入以下代码,Sublime Text 2就会自动安装Package Contr ...

  4. BZOJ 1574&colon; &lbrack;Usaco2009 Jan&rsqb;地震损坏Damage

    Description 农夫John的农场遭受了一场地震.有一些牛棚遭到了损坏,但幸运地,所有牛棚间的路经都还能使用. FJ的农场有P(1 <= P <= 30,000)个牛棚,编号1.. ...

  5. wikioi 2573 大顶堆与小顶堆并用

    题目描写叙述 Description 我们使用黑匣子的一个简单模型.它能存放一个整数序列和一个特别的变量i.在初始时刻.黑匣子为空且i等于0. 这个黑匣子能运行一系列的命令.有两类命令: ADD(x) ...

  6. 小猪猪C&plus;&plus;笔记基础篇(六)参数传递、函数重载、函数指针、调试帮助

    小猪猪C++笔记基础篇(六) ————参数传递.函数重载.函数指针.调试帮助 关键词:参数传递.函数重载.函数指针.调试帮助 因为一些事情以及自己的懒惰,大概有一个星期没有继续读书了,已经不行了,赶紧 ...

  7. Oracle 基于 RMAN 的不完全恢复&lpar;incomplete recovery by RMAN&rpar;

    Oracle 数据库可以实现数据库不完全恢复与完全恢复.完全恢复是将数据库恢复到最新时刻,也就是无损恢复,保证数据库无丢失的恢复.而不完全恢复则是根据需要特意将数据库恢复到某个过去的特定时间点或特定的 ...

  8. (转)Centos搭建FTP服务器

    场景:ftp服务器对于在Linux服务器上进行文件操作太方便,在安装软件时候,大的软件也可以先上传再进行安装! 1 搭建FTP服务器 1.1 检查vsftpd 查看是否已经安装vsftpd rpm - ...

  9. &lbrack;bzoj1717&rsqb;&lbrack;Usaco2006 Dec&rsqb;Milk Patterns 产奶的模式 &lpar;hash构造后缀数组,二分答案&rpar;

    以后似乎终于不用去学后缀数组的倍增搞法||DC3等blablaSXBK的方法了= = 定义(来自关于后缀数组的那篇国家集训队论文..) 后缀数组:后缀数组SA是一个一维数组,它保存1..n的某个排列S ...

  10. ORM框架--GreenDao 3&period;0基本使用指南

    0. ORM框架--GreenDao 3.0基本使用指南 1. Gradle 的配置 这里可以参照官方的文档进行最新的配置(本示例的版本等你看到可能就不是最新的了),但是值得注意的一点是,GreenD ...