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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With