示例
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> }
}
}
我试图这样做,但这不起作用
答案 0 :(得分:0)
public List<string> Data { get; set; }
在XAML中,
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
您想将ItemSsource设置为您在构造函数中创建的ObservableCollection的实例:
YourItemsControL.ItemsSource = Data ;
答案 1 :(得分:0)
还添加DataContext
<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>