[英]WPF Binding to a custom property in a custom control
我有一個自定義文本框,定義如下:
public class CustomTextBox : TextBox
{
public static DependencyProperty CustomTextProperty =
DependencyProperty.Register("CustomText", typeof(string),
typeof(CustomTextBox));
static CustomTextBox()
{
TextProperty.OverrideMetadata(typeof(SMSTextBox),
new FrameworkPropertyMetadata(string.Empty,
FrameworkPropertyMetadataOptions.Journal |
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(CustomTextBox_OnTextPropertyChanged));
}
public string CustomText
{
get { return (string)GetValue(CustomTextProperty); }
set { SetValue(CustomTextProperty, value); }
}
private static void CustomTextBox_OnTextPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
CustomTextBox customTextBox = d as CustomTextBox;
customTextBox.SetValue(CustomTextProperty, e.NewValue);
}
}
我正在綁定XAML中的自定義文本屬性 -
<local:CustomTextBox CustomText="{Binding ViewModelProperty}" />
我面臨的問題是,當我在CustomTextBox中輸入任何內容時,更改不會反映在ViewModelProperty中,即ViewModelProperty沒有得到更新。 CustomTextProperty正在更新,但我想我需要做一些額外的事情來使綁定工作。
我不做什么? 我將不勝感激任何幫助。
謝謝
我想綁定需要雙向。
<local:CustomTextBox
CustomText="{Binding ViewModelProperty, Mode=TwoWay}" />
如果默認情況下使CustomText
屬性綁定為雙向,則無需指定Mode
:
public static readonly DependencyProperty CustomTextProperty =
DependencyProperty.Register(
"CustomText", typeof(string), typeof(CustomTextBox),
new FrameworkPropertyMetadata(
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
您可能還必須為CustomText
屬性定義PropertyChangedCallback,以更新Text
屬性(即您現在實現的其他方向)。 否則,TextBox將不會顯示最初包含在ViewModel屬性中的任何內容,當然,當ViewModel屬性更改時,不會更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.