【发布时间】:2024-04-17 06:15:01
【问题描述】:
我想通过一个属性禁用我的 WPF c# 应用程序中的所有工具提示。我正在以这种方式为我的所有 Windows、UserControls 等使用 ResourceDictionary (MyStyle.xaml):
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Interface;component/MyStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
这是我的 ResourceDictionary MyStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Dupa.Interface.MyStyle">
<Style TargetType="{x:Type ToolTip}">
<Style.Setters>
<Setter Property="Visibility" Value="{Binding Path=TooltipsEnabled, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</Style.Setters>
</Style>
...
</ResourceDictionary>
还有 CodeBehind MyStyle.xaml.cs
public partial class MyStyle : ResourceDictionary, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool tooltipsEnabled;
public MyStyle()
{
InitializeComponent();
TooltipsEnabled = false;
}
public bool TooltipsEnabled
{
get { return tooltipsEnabled; }
set
{
tooltipsEnabled = value;
NotifyPropertyChanged("TooltipsEnabled");
}
}
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
但是绑定不起作用。如果我直接在 MyStyle.xaml 中设置可见性而不绑定,它可以工作:
<Style TargetType="{x:Type ToolTip}">
<Style.Setters>
<Setter Property="Visibility" Value="Collapsed" />
</Style.Setters>
</Style>
我在构建过程中遇到了一些错误:
BindingExpression 路径错误:在“对象”“CalculationViewModel”上找不到“TooltipsEnabled”属性 BindingExpression 路径错误:在“对象”“SettingsViewModel”上找不到“TooltipsEnabled”属性 BindingExpression 路径错误:在“对象”“ControllerViewModel”上找不到“TooltipsEnabled”属性
【问题讨论】:
-
请向我们展示您的“BooleanVisibilityConverter”的代码。如果您打算使用标准转换器,则称为“BooleanToVisibilityConverter”,在 System.Windows.Controls 中定义。
-
抱歉复制和粘贴错误。我的转换器的名称是 BooleanToVisibilityConverter。我在几个地方使用它,它工作正常。我不认为转换器是问题
-
刚刚看到您的编辑,包括错误。您需要在所有 ViewModel 上声明该属性。也许通过定义一个由所有视图模型共享的基本接口。错误信息对我来说似乎很清楚。我认为您不能在样式背后的代码中定义它。无论如何,你在哪里,特别是如何设置属性?
标签: c# .net wpf xaml resourcedictionary