Wpf 如何在xaml中将列表绑定到listbox?
我有一个Wpf 如何在xaml中将列表绑定到listbox?,wpf,list,xaml,binding,listbox,Wpf,List,Xaml,Binding,Listbox,我有一个ObservableCollection和一个ListBox,我想在它们之间进行绑定,但没有在后台代码中使用listBox1.DataSource/ItemsSource=…,我发现了很多这样的示例,但我只需要在xaml代码中进行绑定 如果我没弄错的话,我需要先把我的清单列为财产 private ObservableCollection<ProtectionBase> _listhelmets; public ObservableCollection<P
ObservableCollection
和一个ListBox
,我想在它们之间进行绑定,但没有在后台代码中使用listBox1.DataSource/ItemsSource=…
,我发现了很多这样的示例,但我只需要在xaml代码中进行绑定
如果我没弄错的话,我需要先把我的清单列为财产
private ObservableCollection<ProtectionBase> _listhelmets;
public ObservableCollection<ProtectionBase> ListHelmets
{
get { return _listhelmets; }
set { _listhelmets = value; }
}
public MainWindow()
{
InitializeComponent();
ListHelmets.Add(new Helmet(){protection=5});
ListHelmets.Add(new Helmet() { protection = 7 });
this.DataContext = _listhelmets;
}
private-observecollection\u列表头盔;
公众可观察到的收集列表头盔
{
获取{返回_列表头盔;}
设置{u listhelmets=value;}
}
公共主窗口()
{
初始化组件();
添加(新头盔(){protection=5});
添加(新头盔(){protection=7});
this.DataContext=_listhelmets;
}
xaml代码:
<ListBox x:Name="listhelmets" Height="215" Width="197" PreviewMouseDown="helmet_MouseDown1"
PreviewMouseLeftButtonDown="helmet_PreviewMouseLeftButtonDown"
PreviewMouseMove="helmet_PreviewMouseMove" ItemsSource="{Binding}">
<TextBlock FontWeight="Bold" FontSize="13" Background="Silver" Margin="0 0 0 10" Text="Шлемы"> </TextBlock>
<ListBoxItem >
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=listhelmets, Path=SelectedItem}"
MouseEnter="ChoosingHelmet1"
DragOver="helmet1_DragOver"
DragEnter="helmet_DragEnter" AllowDrop ="true"
DragLeave="helmet_DragLeave" MouseLeftButtonDown="helmet_MouseLeftButtonDown_1">
<TextBlock Text="{Binding protection, ElementName=ListHelmets[0]}" Width="124"/>
</StackPanel>
</ListBoxItem>
<ListBoxItem >
<StackPanel Orientation="Horizontal">
<Image Source="D:..."/>
</StackPanel>
</ListBoxItem>
</ListBox>
如果您不使用MVVM,请在代码隐藏中执行此操作:
ListHelmets.Add(new ProtectionBase(){protection = 5});
ListHelmets.Add(new ProtectionBase() { protection = 7 });
listhelmets.ItemsSource = ListHelmets;
textblock文本保护必须是ProtectionBase类中的属性
在xaml中,执行以下操作:
删除ItemsSource=“{Binding}”,从stackpanel中删除Datacontext,
移除,元素名称=列表头盔[0]
如果您使用的是MVVM,请告诉我这肯定有效: xaml:
我需要mvvm吗?我想在列表框中填入头盔表单ListHelmets,每个头盔都有自己的属性,我想在下面的文本框中显示,event-PreviewMouseLeftButtonDown。现在我已经用括号中不同的[I]为每个listboxitem编写了它,我想这是不对的@RohitYou不需要MVVM。照我前面说的做。现在你只在XAML中做绑定,而不是在代码中。您也可以在XAML中设置DataContext
。@AnjumSKhan那么我应该写什么DataContext=“{Binding…}”
,以及在您的列表框ItemsSource=“{Binding listhalmets}”
。