Aar*_*i S 5 .net c# wpf textbox foreground
当文本在文本框内更改并满足特定条件时,我需要设置文本颜色.我可以使用textbox_textchanged事件从后面的代码实现它,并将brushes.color设置为所需的颜色.
但我无法用xaml wpf方法实现这一点.我是wpf的新手,我不知道在文本框中文本更改时,如何根据特定条件设置文本颜色.
例如:对于给定的文本框,当文本更改时,需要确定输入文本是否为数字,然后将前景色更改为绿色,否则为红色.
期待着帮助.先感谢您.
我不确定您的情况是否允许绑定转换器。但这里有一个解决方案,只需要在后面的代码中绑定转换器。
这是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>
Run Code Online (Sandbox Code Playgroud)
这是视图模型和值转换器
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;
}
}
Run Code Online (Sandbox Code Playgroud)
因此解决方案使用数据触发器来实现目标。此处使用绑定转换器的唯一原因是您需要一个地方来确定哪种值应更改 TextBox 的前景。这里当TextBox的值为“1”时,TextBox的前景将为红色。