(转)WPF Custom Control Dependency Property Gotcha
2011-01-25 10:23
295 查看
原文地址: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:
And the rest of the DP looks like this:
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.
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.
相关文章推荐
- 一站式WPF--依赖属性(DependencyProperty)
- WPF里的DependencyProperty(5)
- WPF里的DependencyProperty(5)
- 一站式WPF--依赖属性(DependencyProperty)二
- [WPF/Silverlight]简单说下CLR Property与WPF Dependency Property的区别
- 在WPF中自定义控件(3) CustomControl (下)
- WPF 依赖属性,用户控件依赖属性(DependencyProperty 依赖属性、GetValue() SetValue() CLR属性包装器、SetBinding 数据绑定)
- 在WPF中自定义控件(3) CustomControl (下)
- ClassLibary和WPF User Control LIbary和WPF Custom Control Libary的异同
- WPF中用户控件对比自定义控件(UserControl VS CustomControl)
- WPF中的Dependency Property(1)
- (转)在WPF中自定义控件 CustomControl (上)
- Recommended Practices for WPF Custom Control Developers
- (转)在WPF中自定义控件 CustomControl (下)注意TemplatePartAttribute
- Silverlight/WPF中DependencyProperty使用陷阱一枚
- WPF里的DependencyProperty(3)
- [WPF] UserControl vs CustomControl
- 在WPF中自定义控件(3) CustomControl (上)
- WPF里的DependencyProperty(4)
- wpf DependencyProperty