在a creating and changing my custom Win 8.1/UWP TextBox control继承TextBox
并连接TextChanged事件后,订阅TextChanged事件时Text属性不准确。
这是我的控制:
[TemplatePart(Name = "PART_ctlTextBox", Type = typeof(TextBox))]
public class CustomTextBox : Control
{
public CustomTextBox()
{
DefaultStyleKey = typeof(CustomTextBox);
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
var textBox = GetTemplateChild("PART_ctlTextBox") as TextBox;
if (textBox != null)
{
textBox.TextChanged += (s, a) => TextChanged?.Invoke(s, a);
}
}
public event TextChangedEventHandler TextChanged;
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CustomTextBox), new PropertyMetadata(null));
}
这是通用的XAML:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customControls="using:CustomControls">
<Style TargetType="customControls:CustomTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="customControls:CustomTextBox">
<TextBox x:Name="PART_ctlTextBox" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, Path=Text, UpdateSourceTrigger=PropertyChanged}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
这是我用来测试它的页面:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock x:Name="lblCustomTextBox" Grid.Row="0" VerticalAlignment="Bottom" />
<local:CustomTextBox Grid.Row="1" x:Name="txtCustomTextBox" TextChanged="customTextBox_OnTextChanged" />
<TextBlock x:Name="lblRegularTextBox" Grid.Row="2" VerticalAlignment="Bottom" />
<TextBox x:Name="txtRegularTextBox" Grid.Row="3" TextChanged="regularTextBox_OnTextChanged"></TextBox>
</Grid>
代码隐藏:
private void customTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
lblCustomTextBox.Text = txtCustomTextBox.Text ?? string.Empty;
}
private void regularTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
lblRegularTextBox.Text = txtRegularTextBox.Text ?? string.Empty;
}
请注意,常规TextBox
会实时更新,而CustomTextBox
会被延迟。我也尝试用Action.Invoke
点击TextChanged但没有用。