How do I set WPF xaml form's Design DataContext to class that uses generic type parameters

偶尔善良 提交于 2019-11-27 02:19:56

问题


Originally my .xaml form used the following line to set the Designer's DataContext where the view model was a non-generic type (note I'm talking about the Design time DataContext not the actual DataContext that will be used at runtime).

<Window ...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
d:DataContext="{d:DesignInstance Dialogs:CustomerSearchDlogViewModel}"
...>

Now instead of CustomerSearchDlogViewModel I have a generic SearchDialogViewModel but I can't figure out what syntax will work in the <Window> tag to let me specify that view model.


回答1:


That is not possible unless the markup extension (DesignInstance) provides properties to pass type arguments, which i doubt. So you might want to subclass as suggested or write your own markup extension which creates generic instances (in fact that is what i am doing right now).

Edit: This extension should do it:

public class GenericObjectFactoryExtension : MarkupExtension
{
    public Type Type { get; set; }
    public Type T { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var genericType = Type.MakeGenericType(T);
        return Activator.CreateInstance(genericType);
    }
}

Initially i had some problems getting the object type from a type-name but you can let the XAML parser resolve the type for you which is neat:

DataContext="{me:GenericObjectFactory Type={x:Type Dialogs:CustomerSearchDlogViewModel`1},
                                      T=Data:Customer}"

(Note the `1 at the end to reference a generic type. If you drop the x:Type wrapping the backtick will cause an error.)




回答2:


A clean option would be to create a new type which just flattens the generic type:

public class CustomerSearchDialogViewModel : SearchDialogViewModel<Customer> 
{
}


来源:https://stackoverflow.com/questions/8235421/how-do-i-set-wpf-xaml-forms-design-datacontext-to-class-that-uses-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!