NullOrEmptyConverter 类
public class NullOrEmptyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return true;
if (value is string && value.ToString().Trim() == string.Empty) return true;
return false;
}
public object ConvertBack(object value, Type targetType, object paramter, CultureInfo culture)
{
throw new InvalidOperationException("IsNullConver can only be used oneWay.");
}
}
样式:Global.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:TextStyleResource="clr-namespace:WpfApplication1"
mc:Ignorable="d"
>
<TextStyleResource:NullOrEmptyConverter x:Key="nullOrEmptyConverter"/>
<Style x:Key="Style_TextBox" TargetType="{x:Type TextBox}">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="Margin" Value="20,8,0,0"/>
</Style>
<Style x:Key="Stype_ReadOnlyTextBox" TargetType="{x:Type TextBox}" BasedOn="{StaticResource Style_TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self},Path=Text,Converter={StaticResource nullOrEmptyConverter}}" Value="False">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=Text}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
APP.xmal注册样式
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Global.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
MainWindow中对绑定的值实现ToolTipe验证,为空 不显示ToolTipe
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication1"
Name="win"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="TxtTextBox" Width="200" Height="40" Style="{StaticResource Stype_ReadOnlyTextBox}"
Text="{Binding ElementName=win,Path=DsiplayStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>
</Grid>
</Window>
定义绑定的属性
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window,INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
this.DsiplayStr = "ABCDEFGH";
}
private string _dsiplayStr;
public string DsiplayStr
{
get { return _dsiplayStr; }
set {
_dsiplayStr = value;
PropertyChanged(this,new PropertyChangedEventArgs("DsiplayStr"));
}
}
}