如果我有一个包含静态变量的类,该静态变量将包含Tooltip的Visiblity状态,那么当visiblity变量发生变化时,如何编写代码隐藏以动态更改Tooltip可见性?
即。禁用“工具提示”选项时,不应显示工具提示,但启用“工具提示”选项后,应显示工具提示。 (工具提示选项保存在不同类中的静态变量中)动态创建工具提示及其连接的控件。
伪代码:
ToolTip myToolTip = new ToolTip();
Visiblity tooltipVis = Visibility.Visible;
Bind myToolTip.Visiblity to toolTipVis
//Any control with ToolTip should now show their respective ToolTip messages.
...
tooltipVis = Visibility.Hidden;
//Any control with ToolTip should now have ToolTip messages disabled
尝试绑定到TreeViewItem:
TreeViewItem tvi = new TreeViewItem() { Header = tviHeader };
ToolTip x = new System.Windows.Controls.ToolTip();
x.Content = "This is text.";
Binding binder = new Binding {
Source = EnvironmentalVariables.ToolTipVisibility,
Path = new PropertyPath("Visibility")
};
x.SetBinding(VisibilityProperty, binder);
user.ToolTip = x;
public class EnvironmentalVariables {
public static Visibility ToolTipVisibility { get; set; }
}
这似乎没有将Visiblity绑定到EnvironmentalVariables.ToolTipVisibility变量。
答案 0 :(得分:1)
您可以使用ToolTipService.IsEnabled Attached Property。
<TextBlock Text="Example" ToolTip="This is an example"
ToolTipService.IsEnabled="{Binding TooltipEnabled, Source={x:Static Application.Current}}">
因为你无法绑定到静态属性(in WPF Version 4.5 you can),我会使用这种解决方法从任何地方访问该属性
public partial class App : Application, INotifyPropertyChanged
{
private bool _tooltipEnabled;
public bool TooltipEnabled
{
get { return _tooltipEnabled; }
set
{
if (_tooltipEnabled != value)
{
_tooltipEnabled = value;
RaiseNotifyPropertyChanged("TooltipEnabled");
}
}
}
private void RaiseNotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
答案 1 :(得分:0)
只需删除您创建的Path
对象中的Binding
属性即可。
这就是它需要工作的全部。
EnvironmentalVariables.ToolTipVisibility = System.Windows.Visibility.Collapsed;
var b = new Button () { Content = "test" };
var x = new ToolTip();
x.Content = "This is text.";
var binding = new Binding {
Source = EnvironmentalVariables.ToolTipVisibility,
};
x.SetBinding(VisibilityProperty, binding);
b.ToolTip = x;
如果要在运行时动态更改ToolTipVisibility,则必须实现属性通知。