我正在实现一个UserControl
名为 PhoneBox,它包含一个单一的TextBox
、一些自定义逻辑,并且有一个名为 PhoneNo 的 DependencyProperty。LostFocus
它将在带有for的双向绑定场景中使用UpdateSourceTrigger
。所以我写了以下代码 -
XAML(用户控件):
<StackPanel>
<TextBox Name="txtPhone" MinWidth="120" MinHeight="23" LostFocus="txtPhone_LostFocus" GotFocus="txtPhone_GotFocus"/>
</StackPanel>
代码隐藏(用户控件):
public partial class PhoneBox : UserControl
{
//Some Code
static PhoneBox()
{
FrameworkPropertyMetadata phoneNoMetadata =
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnPhoneNoChanged),
new CoerceValueCallback(CoercePhoneNoValue));
PhoneNoProperty = DependencyProperty.Register("PhoneNo", typeof (string), typeof (PhoneBox),
phoneNoMetadata,
new ValidateValueCallback(ValidatePhoneNoValue));
}
public readonly static DependencyProperty PhoneNoProperty;
public string PhoneNo
{
get { return (string)GetValue(PhoneNoProperty); }
set { SetValue(PhoneNoProperty, value); }
}
private static void OnPhoneNoChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PhoneBox phoneBox = (PhoneBox)d;
string newValue = (string)e.NewValue;
phoneBox.txtPhone.Text = newValue;
}
private static object CoercePhoneNoValue(DependencyObject d, object basevalue)
{
return basevalue;
}
private static bool ValidatePhoneNoValue(object value)
{
return true;
}
private void txtPhone_LostFocus(object sender, RoutedEventArgs e)
{
this.SetValue(PhoneNoProperty, this.txtPhone.Text);
}
private void txtPhone_GotFocus(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtPhone.Text))
this.txtPhone.Text = this.FilterText(txtPhone.Text);
}
private string FilterText(string text)
{
//Some cutom logic
}
//Some more Code
}
XAML(消费者):
<pbc:PhoneBox PhoneNo="{Binding Path=User.Phone, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>
有用。但我的问题是,我使用txtPhone_LostFocus
事件处理程序设置属性值(进而更新源)的方式是否合适?有没有更合适的方法来做到这一点?我是这个DependencyProperty
东西的新手,所以任何指导,建议,评论将不胜感激。