Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a UserControl in MVVM pattern?

Tags:

wpf

mvvm-light

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

like image 827
user8023045 Avatar asked Mar 07 '23 07:03

user8023045


1 Answers

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:

like image 152
tabby Avatar answered Apr 09 '23 09:04

tabby