使用XAML属性中定义的自定义转换器动态加载XAML

时间:2019-03-11 13:04:24

标签: c# wpf xaml

我正在尝试从字符串/文件动态加载XAML。问题是XAML包含一些自定义转换器的引用,并且在加载时会失败,并显示错误

System.Windows.Markup.XamlParseException:”无法创建未知类型'{clr-namespace:DataGridApp.Converter} CollectionConverter'

我的动态XAML很简单

<UserControl 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:converter="clr-namespace:DataGridApp.Converter">
    <UserControl.Resources>
        <converter:CollectionConverter x:Key="CollectionConverter"/>
    </UserControl.Resources>
    <Grid>
            <DataGrid
                      ItemsSource='{Binding Path=dynamicProperty, Converter={StaticResource CollectionConverter}}'/>
    </Grid>
</UserControl>

用于动态读取XAML的C#代码

private FrameworkElement LoadViewFromMemory(string template)
{
   using (Stream s = new MemoryStream(Encoding.Default.GetBytes(template)))
    {
       return XamlReader.Load(s) as FrameworkElement;
    }
}

Converter类将任何对象简单地转换为对象的集合

public class CollectionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            List<dynamic> d = new List<dynamic> {value};
            return d;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return false;
    }
}

是否可以通过转换器动态加载XAML?

答案:

如@mike所建议,我必须在XAML clr-namespace中为转换器添加程序集引用

<UserControl 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:converter="clr-namespace:DataGridApp.Converter;assembly=DataGridAppProj">  

0 个答案:

没有答案