240
一线老司机

(转)WPF Custom Control Dependency Property Gotcha

原文地址:http://geekswithblogs.net/thibbard/archive/2008/04/22/wpf-custom-control-dependency-property-gotcha.aspx

 

Let's say you have a custom WPF control called SearchTextBox.  It has a textbox and a button labeled "search".  Simple enough, you reuse it in your application when you want to provide search. 

Then one day, you decide you need this control needs to be bindable.  So you expose a public property Text and map it to textSearch just like you would in WinForms.

Well, that doesn't work, so you google around and stumble upon Dependency Properties and learn how to create your own (VS snippet shortcut propdb) and create a Text DP.

Now you spend 30 minutes trying to map your Text DP to your textSearch.Text until you finally figure out that your DP snippet lead you astray and there is one more step that didn't get included in the shortcut.  In the UIPropertyMetaData, you need to specify a function to call when the property changes - so you can set textSearch.Text.

The function looks like this:

static void textChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args) { SearchTextBox searchTextBox = (SearchTextBox)property; searchTextBox.textSearch.Text= (string)args.NewValue; }

And the rest of the DP looks like this:

public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(string), typeof(SearchTextBox), new UIPropertyMetadata(string.Empty, new PropertyChangedCallback(textChangedCallBack)));

The important part here is what wasn't created by the VS snippet :

new UIPropertyMetadata(string.Empty, new PropertyChangedCallback(textChangedCallBack))

Now you are binding to your custom control and all is good.

posted @   明年我18  阅读(510)  评论(0编辑  收藏  举报
编辑推荐:
· 聊一聊 C#前台线程 如何阻塞程序退出
· 几种数据库优化技巧
· 聊一聊坑人的 C# MySql.Data SDK
· 使用 .NET Core 实现一个自定义日志记录器
· [杂谈]如何选择:Session 还是 JWT?
阅读排行:
· 字节豆包,来园广告
· 一个.NET开源、易于使用的屏幕录制工具
· 【经验】几种数据库优化技巧
· 我用cursor, 半就开发了一个手机壁纸小程序,真的太强了
· 聊一聊 C#前台线程 如何阻塞程序退出
点击右上角即可分享
微信分享提示