[英]ControlTempate wpf Textbox not showing text and trigger properties
我正在使用C#WPF中的一个小项目继续学习。 我当前的情况是,当用户输入发生错误时,例如,无法将其输入解析为十进制数,我想更改TextBox
的边框。
经过一番阅读后,我使用了控件模板,下面是XAML ,但是当我运行项目时,使用控件模板( TextBox1 )的TextBox
没有显示任何文本,并且看不到我做错了什么。 有人可以帮忙吗?
我也在学习时就用IsMouseOver
属性触发了更改,但是在我的项目中,我想触发一个error属性,所以在我看来,我需要向我的TextBox
控件中添加一个属性IsError
作为bool并在我的代码后面当我测试用户输入并且解析失败时,我会将TextBox
属性IsError
设置为true,这将触发ControlTemplate
更改。 但是,可以这样做吗?或者有更站立的方法吗? 谢谢。
ControlTemplate
XAML
<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
,您不需要一个全新的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
,并在TextBoxes上使用Grid.Row
和Grid.Column
附加属性指定它们在您的位置。视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.