文本框不显示文本和触发器属性
本文关键字:文本 触发器 属性 显示 | 更新日期: 2023-09-27 18:12:13
我正在用c# WPF继续我的学习。我目前的情况是,当用户输入发生错误时,我想更改TextBox
的边界,例如无法将其输入解析为十进制数。
经过一些阅读,我使用了一个控制模板,XAML在下面,但是当我运行项目的TextBox
使用控制模板(textBox1)不显示任何文本,我看不出我做错了什么。有谁能帮忙吗?
我也触发了一个IsMouseOver
属性的变化,就在我学习的时候,但在我的项目中,我想触发一个错误属性,所以在我的脑海中,我需要添加到我的TextBox
控制属性IsError
作为一个bool,在我的代码后面,当我测试用户输入,它失败的解析,我会设置TextBox
属性IsError
为真,这将触发ControlTemplate
的变化。然而,这是可以做到的,或者有一个更站得住脚的方法来做到这一点?谢谢。
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>
首先,模板定义控件的呈现方式。他们定义了他们的整体形象。
你告诉TextBox
用另一个不同的TextBox
来渲染自己。这意味着你在应用程序中看到的TextBox
实际上不是你在Grid
中定义的那个,带有"Testing1"文本,而是你在没有文本集的ControlTemplate
中定义的那个。
但除此之外,你不需要一个全新的ControlTemplate
。你只需要一个Style
:
<Window.Resources>
<Style TargetType="TextBox" x:Key="OnError">
<Setter Property="FontSize" Value="28" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="BorderBrush" Value="Silver" />
<Setter Property="Height" Value="50" />
<Setter Property="Width" Value="120" />
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="BorderThickness"
Value="5" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Text="Tesing1" Margin="146,23,0,0" Name="textBox1" Style="{StaticResource OnError}" />
<TextBox Text="Testing2" Height="23" HorizontalAlignment="Left" Margin="12,23,0,0" Name="Test1" VerticalAlignment="Top" Width="120" />
</Grid>
另外,在WPF中,你通常不使用Margin
来创建布局:p相反,你应该添加ColumnDefinitions和RowDefinitions到你的Grid
,并使用Grid.Row
和Grid.Column
附加属性在你的文本框上指定它们在你的视图中的位置。