4

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

3
  • What I want to know is how to bind MyView.xaml in my Project View folder to <UserControl> above. The link you provided is not listed on this question. Commented Dec 22, 2017 at 6:02
  • show us your VIewList Commented Dec 22, 2017 at 6:11
  • How to add a property to the View List The question is whether you can add a View in the actual UI by adding code in the ViewModel. Commented Dec 22, 2017 at 6:17

1 Answer 1

7

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.