gpt4 book ai didi

c# - 完成WPF中TextBox触发事件的工作

转载 作者:太空宇宙 更新时间:2023-11-03 22:13:52 25 4
gpt4 key购买 nike

您好,我正在尝试将我正在做的事情放在代码隐藏事件的触发器中,该样式正在应用于文本框。我想要的是防止使用代码隐藏来执行此操作并使用触发器。有什么办法可以做到这一点?

我的文本框

<TextBox Name="myTextBox"  Style="{StaticResource txtBoxStyle}"/>

我的风格

<Style x:Key="txtBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Silver"/>
<Setter Property="MaxLength" Value="6"/>
</Style>

代码隐藏事件

private void myTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (myTextBox.Text.Length == 0)
myTextBox.Text = "000000";
}

private void myTextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (myTextBox.Text == "000000")
myTextBox.Clear();
}

private void myTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (!(e.Key >= Key.D0 && e.Key <= Key.D9) && e.Key != Key.Back)
e.Handled = true;
}

private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (myTextBox.Text == "000000")
myTextBox.Foreground = Brushes.Silver;
else
{
myTextBox.Foreground = Brushes.Black;

if(myTextBox.Text.Length == 6)
myButton.Visibility = Visibility.Visible;
else
myButton.Visibility = Visibility.Hidden;
}
}

提前致谢!

最佳答案

编辑: 对此逻辑使用触发器不是一个好主意,并且由于其自引用(导致堆栈溢出)很可能会失败,值转换器也有点问题。要封装复杂逻辑并通过 Style 应用它,请使用 attached behavior .


<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsFocused, RelativeSource={RelativeSource Self}}" Value="False"/>
<Condition Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value=""/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="Text" Value="000000"/>
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsFocused, RelativeSource={RelativeSource Self}}" Value="True"/>
<Condition Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="000000"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="Text" Value=""/>
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<Trigger Property="Text" Value="000000">
<Setter Property="Foreground" Value="Silver"/>
</Trigger>
</Style.Triggers>
<!-- If (Text != "000000") Foreground = Brushes.Black -->
<Setter Property="Foreground" Value="Black"/>
</Style>

设置按钮可见性的逻辑不应该用这种风格来处理,而应该由按钮来处理。无法翻译按键事件。

按钮样式:

<Style TargetType="{x:Type Button}">
<Setter Property="Visibility" Value="Hidden"/> <!-- Normal state -->
<Style.Triggers>
<DataTrigger Binding="{Binding Text.Length, ElementName=myButton}" Value="6">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>

关于c# - 完成WPF中TextBox触发事件的工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com