我正在致力于为 Windows 8.1 Universal/UWP 的 XAML 应用创建自定义控件,并不断发现细微差别。我似乎找不到任何有关创建现有控件(如 TextBox)的自定义实现的优秀教程,因此我一直在浏览 Telerik 等控件的源代码,尝试了解其自定义控件的工作原理。
我遇到的最新问题是,如果光标不停留在条目开头,就无法创建最简单的自定义文本框。当我继续输入文本时,即使文本被附加到末尾,光标仍停留在开头。我通过在模拟器下面添加一个正常运行的常规文本框来验证这不是模拟器的问题。我确信这与我创建自定义控件的方式有关。
这是我的控制:
public class CustomTextBox : TextBox
{
public CustomTextBox()
{
DefaultStyleKey = typeof(CustomTextBox);
}
}
这是我的 Generic.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 Text="{TemplateBinding Text}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
最后,这是我的页面 XAML,显示了运行它并在第一个文本框中输入文本时出现的问题。 TextBlock 可以显示我输入的文本的实时更改,这对于我最初遇到的问题至关重要:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding ElementName=txtTextBox, Path=Text}" Grid.Row="0" VerticalAlignment="Bottom" />
<local:CustomTextBox Grid.Row="1" x:Name="txtTextBox" />
<TextBox Grid.Row="2"></TextBox>
</Grid>
我尝试更改绑定(bind)以使用 TwoWay 绑定(bind):
{Binding RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, Path=Text}
我还尝试订阅 TextChanged 事件并根据新文本执行 Select 来尝试移动光标,但这些都不起作用:
private void CustomTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
Select(Text.Length, 0);
}
更新
更改为从 Control 继承后,
我又回到了原来的问题。订阅 TextChanged 事件时,我无法实时更新 Text 属性。我a created a new thread因为它走的是与此不同的道路。
旁注:我什至尝试从 TextBox
继承的原因是因为这就是 Telerik 的 RadTextBox 控件的实现方式。
最佳答案
正如 @lokusking 提到的,将 TextBox
嵌套在另一个 TextBox
中并不是正确的方法,因为您的 CustomTextBox
继承自 TextBox
,您需要自定义您的 ControlTemplate
,如 TextBox styles and templates .
您可以复制TextBox
的默认模板并替换为您的CustomTextBox
并尝试一下,它会解决您的问题。您也可以创建自己的模板,例如:Create Your First WinRT WatermarkTextBox Control 。但不要在 CustomTextBox
中嵌套另一个 TextBox
,您可以引用此线程中的答案:Why use a templated control over a UserControl? ,它很好地解释了我们在何处以及为何使用模板化控件。
如果你想注册其他属性,可以使用 DependencyProperty ,如果您想注册新的事件,可以引用Custom events and event accessors in Windows Runtime Components .
关于c# - XAML 自定义文本框光标停留在输入开始处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187278/