【发布时间】:2015-09-10 13:47:04
【问题描述】:
我将继续学习 C# WPF 中的一个小项目。我目前的情况是我想在用户输入发生错误时更改TextBox 的边框,例如无法将他们的输入解析为十进制数。
经过一番阅读,我使用了一个控件模板,XAML 在下面,但是当我使用控件模板(textBox1)运行项目时,TextBox不显示任何文字,我看不出我做错了什么。有人可以帮忙吗?
我还在学习时使用IsMouseOver 属性触发更改,但在我的项目中我想触发一个错误属性,所以在我看来我需要添加到我的TextBox 控制属性@ 987654325@ 作为 bool 并且在我的代码后面,当我测试用户输入并且解析失败时,我会将 TextBox 属性 IsError 设置为 true,这将触发 ControlTemplate 更改。但是,这可以做到还是有更稳定的方法来做到这一点?
谢谢。
XAML of ControlTemplate
<Window x:Class="TestContentStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="StyleTriggersSample" Height="100" Width="300">
<Window.Resources>
<!--A ControlTemplate for textbox including error-->
<ControlTemplate TargetType ="TextBox" x:Key="OnError">
<TextBox Name="TextBox"
FontSize="28"
HorizontalAlignment="Center"
VerticalAlignment="Center"
BorderBrush="Silver"
BorderThickness="1"
Height="50"
Width="120"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter TargetName="TextBox"
Property="BorderThickness"
Value="5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<Grid>
<TextBox Text="Tesing1" Margin="146,23,0,0" Name="textBox1" Template="{StaticResource OnError}" />
<TextBox Text="Testing2" Height="23" HorizontalAlignment="Left" Margin="12,23,0,0" Name="Test1" VerticalAlignment="Top" Width="120" />
</Grid>
【问题讨论】:
-
您可以使用 WPF 附带的内置验证来完成此操作
-
验证方法示例我看到所有使用的视图模型,坦率地说,对我来说是先进的
-
您在
ControlTemplate的ControlTemplate中使用了TextBox,这没有任何意义。