如何在 C# 中将扩展器添加到 ViewModel 的视图中?

How to add Expanders to View from ViewModel in C#?

我尝试将扩展器元素从我的 ViewModel 动态添加到我的视图。这是我使用 Prism 的可绑定基础的视图模型:

public class MyViewModel : BindableBase
    {
        public MyViewModel()
        {
            MyExpanders = new List<Expander>();
            AddAllExpanders();
        }

        private void AddAllExpanders()
        {
            AddExpander("First expander header", "First expander content");
            AddExpander("Second expander header", "Second expander content");
        }

        private void AddExpander(string header, string content)
        {
            var expander = new Expander();
            expander.Header = header;
            expander.HorizontalAlignment = HorizontalAlignment.Stretch;
            expander.Margin = new Thickness(10);
            expander.Background = Brushes.LightGray;
            expander.IsExpanded = false;
            expander.Content = content;
            MyExpanders.Add(expander);
        }

        private List<Expander> _myExpanders;
        public List<Expander> MyExpanders
        {
            get { return _myExpanders; }
            set { SetProperty(ref _myExpanders, value); }
        }
    }

这是我的观点:

<UserControl x:Class="MyProject.Views.MyView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyProject.Views"
             x:Name="Info"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="1">
            <ContentControl Content="{Binding MyExpanders}"/>
        </StackPanel>
    </Grid>
</UserControl>

这只显示“(Sammlung)”,即英文的“collection”:

我错过了什么?

如果你想绑定它,你需要使用 ObservableCollection<> 而不是 List<>

试试这个:

    private ObservableCollection<Expander> myExpanders;

    public ObservableCollection<Expander> MyExpanders
    {
        get => this.myExpanders;
        set => SetProperty(ref this.myExpanders, value);
    }

在 XAML 中,我将通过使用 Itemscontrol 来完成此操作:

    <ItemsControl  ItemsSource="{Binding MyExpanders}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>