前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(转)WPF Custom Control Dependency Property Gotcha

(转)WPF Custom Control Dependency Property Gotcha

作者头像
明年我18
发布2019-09-18 11:45:12
3170
发布2019-09-18 11:45:12
举报
文章被收录于专栏:明年我18明年我18明年我18

原文地址: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.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011-01-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档