【发布时间】:2017-03-18 11:19:53
【问题描述】:
我有带有默认 BorderBrush 的 WPF 文本框。当 TextBox 有空内容时,我想将 BorderBrush 更改为红色。这是我的代码:
<TextBox Width="200" Text="{Binding Path=Description}" Name="tbDescription" Grid.Row="1" Grid.Column="2" Margin="2"
BorderBrush="{Binding RelativeSource={RelativeSource Self},
Path=Text,
Converter={StaticResource borderBrushColorConverter}}">
这是我的转换器:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = value as string;
if (string.IsNullOrEmpty(text))
return Brushes.Red;
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
问题是只有在失去TextBox焦点时边框才会变成红色。我尝试在 Background 属性上使用相同的代码,而不是在 BorderBrush 上,然后一切正常。
【问题讨论】:
-
问题是,默认情况下,WPF 在文本框获得焦点时会在文本框周围添加一个蓝色边框。您应该尝试寻找去除该边框的方法。试试这个链接:(stackoverflow.com/questions/6404059/…)
-
如果您将绑定模式更改为
PropertyChanged而不是默认的LostFocus是否有效?Text="{Binding Path=Description, Mode=PropertyChanged}" -
这里不要使用转换器,使用
Style和DataTrigger。
标签: c# wpf binding textbox converter