如何将导入的字符串的ObservableCollection绑定到ItemsControl

本文关键字:绑定 ItemsControl ObservableCollection 字符串 导入 | 更新日期: 2023-09-27 17:52:12

示例

class abc
{
 public ObservableCollection<string> Data { get; set; }
//data will be initialized in some functions
}

wpf应用

namespace WpfApplication
{
public partial class MainWindow : Window
{
    [Import(typeof(GateManager))]
    public abc _abc { get; set; }
   public MainWindow()
    {
        InitializeComponent();

    }
} 
public void OnImportsSatisfied()
    {
        var binding = new Binding
        {
            Source = _abc,
            Path = new PropertyPath("Data")
        };
       databox.SetBinding(ItemsControl.SourceProperty, binding);  
   //databox is name of the ItemControl like                                //<ItemsControl x:Name="databox" ScrollViewer.VerticalScrollBarVisibility="Auto">
   //   <ItemsControl.ItemTemplate>
     //        <DataTemplate>
              // <StackPanel Orientation="Horizontal">
               //    <TextBlock Text="{Binding}" />
             //  </StackPanel>
         //  </DataTemplate>
      //</ItemsControl.ItemTemplate>
  //</ItemsControl>      }
 }
}

我试着这样做,但这不起作用

如何将导入的字符串的ObservableCollection绑定到ItemsControl

同时添加数据上下文

<Window.DataContext>
    <ViewModel:ManageUserViewModel/>
</Window.DataContext> 

在cs文件中:

private ObservableCollection<UserType> _listUserTypes = new ObservableCollection<UserType>();
            public ObservableCollection<UserType> UserTypes
            {
                set
                {
                    _listUserTypes = value;
                }
                get
                {
                    return _listUserTypes;
                }
            }

在Xaml:中

<ItemsControl ItemsSource="{Binding Path=UserTypes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
public List<string> Data { get; set; }

在XAML、中

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

您想将ItemSource设置为您在构造函数中创建的ObservableCollection的实例:

YourItemsControL.ItemsSource  = Data ;