Issue with ToolTip bound to a dependency property
I am facing an issue with ToolTips (again!)..
My code is as follows:
Xaml file:
<Grid>
<Button Height="23" Margin="82,0,120,105" Name="button1" VerticalAlignment="Bottom" ToolTip="{Binding Path=Label, Mode=Default}">Button</Button>
</Grid>
cs file:
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1开发者_开发百科 : Window
{
Parameter p1;
System.Timers.Timer aTimer;
public Window1()
{
InitializeComponent();
p1 = new Parameter();
p1.Label = "One thing";
this.DataContext = p1;
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
aTimer.Interval = 5000;
aTimer.Enabled = true;
}
void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
aTimer.Enabled = false;
p1.Label = null;
}
}
The Parameter class is as follows:
class Parameter : System.ComponentModel.INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
#endregion
private string label = String.Empty;
public string Label
{
get { return label; }
set
{
label = value;
OnPropertyChanged(new PropertyChangedEventArgs("Label"));
}
}
private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
{
try
{
if (PropertyChanged != null)
{
PropertyChanged(this, propertyChangedEventArgs);
}
}
catch (Exception exc)
{
}
}
}
Now after the button is clicked, I get the tooltip "One thing" but after 5 seconds, I get an empty tooltip for sometime. Since I set the dependency property to null, I had expected no tooltip.
Afterwards, if I hover the mouse over the button, I get no empty ToolTip (as expected). Its only during the change of value I get the empty ToolTip.
Can you please help.
Try this... change your Label
property and _label
variable to type object
instead of string
i.e. use it as string but declare it as an object
.
I guess the problem above happens because null
string is actually string.Empty
and ToolTip
is of object type. The boxing that happens assumes null string as string.empty
and hence shows a empty tooltip instead of no tooltip. But if Label
is object tyupe then null value will represent no ToolTip
.
If the suggested data type change of the Label
property is not allowed in your case then then use a Converter
in the Label
binding to return null object for empty string.
Let me know if this helps.
精彩评论