当文本框内的文本发生变化并满足特定条件时,我需要设置文本颜色。我可以通过 textbox_textchanged 事件和 set brushes.color 将其设置为所需的颜色,从代码中实现这一点。
但我无法使用 xaml wpf 方法来实现它。我是 wpf 的新手,我不确定当文本框中的文本发生变化时如何根据特定条件设置文本颜色。
例如:对于给定的文本框,当文本更改时,它需要确定如果输入文本是数字,则将前景色更改为绿色或红色。
期待帮助。提前谢谢你。
最佳答案
我不确定在您的情况下是否允许绑定(bind)转换器。但这里有一个解决方案,只需要在您的代码后面有一个绑定(bind)转换器。
这是xaml中的代码
<Grid.Resources>
<local:ValueConverter x:Key="ValueConverter"></local:ValueConverter>
</Grid.Resources>
<TextBox Text="{Binding Text,UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Text,Converter={StaticResource ValueConverter}}" Value="True">
<Setter Property="TextBox.Foreground" Value="Red"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
这是 View 模型和值转换器
public class ViewModel : INotifyPropertyChanged
{
private string _text;
public string Text
{
get
{
return this._text;
}
set
{
this._text = value;
if (null != PropertyChanged)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class ValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (null != value)
{
if (value.ToString() == "1")
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
因此该解决方案使用数据触发器来实现目标。在这里使用绑定(bind)转换器的唯一原因是您需要一个地方来确定应该更改 TextBox 前景的值类型。这里TextBox的值为“1”时,TextBox的前景为红色。
关于c# - 当文本更改并满足特定条件时更改文本框的前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16986105/