为什么我会在 xaml 中收到“Windows Presentation Foundation(WPF) 项目不支持 BoolToRowHeightConverter 错误?

Why would I get a "BoolToRowHeightConverter is not supported in a Windows Presentation Foundation(WPF) project error in xaml?

为什么我会在 xaml 中收到“Windows Presentation Foundation(WPF) 项目不支持 BoolToRowHeightConverter 错误? 我使用转换器根据扩展器的 IsExpanded 属性.

在网格中将 rowheight 转换为 * 和 Auto

xaml中的代码:

     <RowDefinition Height="{Binding IsExpanded, ElementName=Expander5, Converter={x:Static BoolToRowHeightConverter.Instance}}"/>

xaml.cs中的代码:

    public class BoolToRowHeightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object   parameter, System.Globalization.CultureInfo culture)
        {
            if ((bool)value) return new GridLength(1, GridUnitType.Star);
            else
                return GridLength.Auto;

        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }


    }

您已决定使用 x:Static 标记扩展 ({x:Static BoolToRowHeightConverter.Instance}) 来引用值转换器,但您还需要提供您引用的实际字段或 属性 ( Instance)。为此,您需要将其添加到 BoolToRowHeightConverter class:

public class BoolToRowHeightConverter : IValueConverter
{

  // Convert and ConvertBack methods ...

  public static readonly BoolToRowHeightConverter Instance = new BoolToRowHeightConverter();

}

通常,IValueConverters 是这样使用的:

a) 在您的 XAML 页面中添加一个引用您的转换器 class 的命名空间...通常看起来像这样:

xmlns:Converters="clr-namespace:WpfApplication1.Converters"

b) 将转换器实例 class 添加到页面的 Resources 部分(或 App.xaml:

<Window.Resources>
    <Converters:BoolToRowHeightConverter x:Key="BoolToRowHeightConverter" />
    ...
</Window.Resources>

c) 通过您给它的 x:Key 值引用您的转换器实例:

<RowDefinition Height="{Binding IsExpanded, ElementName=Expander5, 
    Converter={StaticResource BoolToRowHeightConverter}}" />