user8023045
user8023045

Reputation: 115

How to dynamically add a UserControl in MVVM pattern?

This is a sample source to help explain my explanation

<ItemsControl ItemsSource="{Binding PaggingButtonList}">            
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <UserControl Name="{Binding ViewName}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

I want to dynamically add as in the code above. Unfortunately, the only way to add a View I know is to . So I want to know what to assign to what? Section in to dynamically find and add View file of my project. Thank you

enter image description here

Upvotes: 4

Views: 3599

Answers (1)

tabby
tabby

Reputation: 1918

You can use ContentControl to host your UserControl:

 <ItemsControl ItemsSource="{Binding ViewList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ContentControl Content="{Binding Name,Converter={StaticResource NameToContentConverter}}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Define ObservableCollection:

public ObservableCollection<object> ViewList { get; set; } = 
  new ObservableCollection<object>();

and to add Content later

ViewList.Add(new View() { Name = "yourUserControlName" });

Your View Class:

public class View
{
    public string Name { get; set; } = "";
}

Since ContentControl.Content expect object and you are passing it as a string you can use Converter.

Converter:

public class NameToContentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value != null)
        {
            Type userControl =  Type.GetType(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name +"."+ value,null,null);
            return Activator.CreateInstance(userControl);
        }
        return "";
    }

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

to know more about Activator see here

Output:

Upvotes: 7

Related Questions