【发布时间】:2016-11-15 09:00:02
【问题描述】:
我有一个带有一些视图 (xaml) 的 WPF C# 应用程序,尤其是一个选项视图。在这个视图中,有一个复选框可以隐藏所有按钮。
这个问题,怎么办?
我有一个MainStyle.xaml,它是一个ResourceDictionary,包含所有样式、转换器等。我的方法是在这个文件中设置一个样式,比如:
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed" />
</Style>
这可行,但用户应决定按钮是否可见。所以我必须将样式绑定到复选框。
第一步是将样式绑定到 ResourceDictionary (MainStyle.xaml) 后面的代码。但它不起作用。我已将构造函数中的属性设置为 false,但按钮是可见的。
MainStyle.xaml
<Style TargetType="Button">
<Setter Property="Visibility"
Value="{Binding ButtonsEnabled, RelativeSource={RelativeSource AncestorType=ResourceDictionary}, Converter={StaticResource BooleanVisibilityConverter}}" />
</Style>
代码隐藏 (MainStyle.xaml.cs)
public partial class BaseStyle : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public BaseStyle()
{
InitializeComponent();
ButtonsEnabled = false; // for testing
}
private Boolean buttonsEnabled;
public bool ButtonsEnabled
{
get { return buttonsEnabled; }
set
{
buttonsEnabled = value;
NotifyPropertyChanged("ButtonsEnabled");
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
如果绑定有效,第二步是将 ResourceDictionary 中的样式绑定到选项视图。
【问题讨论】:
-
首先检查您的 VS 输出窗口以搜索失败的绑定。然后启动 Snoop 并检查按钮的 Visibility 属性以查看它是否失败(以红色突出显示)。如果您能找出实际失败的原因,那么您就可以开始提出正确的解决方案了。