【发布时间】:2012-10-26 16:22:50
【问题描述】:
我在 WPF 项目的 XAML 中使用布尔转换器。我想在“IsBusy”为真时禁用一些按钮。我绝对确定 IsBusy 已正确设置为 true/false。我能够在没有转换器的情况下成功地直接绑定到 IsBusy。以下内容目前不起作用。我已经在实际的转换器类中放置了断点,并且永远不会命中“Convert”和“ConvertBack”方法。这里有什么问题?
IsEnabled="{Binding IsBusy, Converter={StaticResource InvertedBooleanConverter}}"
资源:
<Window.Resources>
<converters:InvertedBooleanConverter x:Key="InvertedBooleanConverter" />
</Window.Resources>
转换器:
xmlns:converters="clr-namespace:MyProject.Converters"
转换器:
namespace MyProject.Converters
{
[ValueConversion(typeof(bool), typeof(bool))]
public class InvertedBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
}
【问题讨论】:
-
在这些情况下,我认为您必须退后一步——添加
<TextBlock Text="{Binding}" />并确保它显示正确的类(包含 IsBusy 的类)。 -
@dbaseman 编辑澄清我能够在没有转换器的情况下成功绑定到 IsBusy。我还在同一个 xaml 的其他地方成功绑定到它。
-
@dbaseman 我尝试了您的建议,但 TextBlock 中没有出现任何内容。也许我的 DataContext 搞砸了。
-
@dbaseman 我将按钮的数据上下文正确设置为模型。现在按预期工作。如果您将其添加为答案,我将很乐意接受。谢谢。