【发布时间】:2016-03-31 04:51:27
【问题描述】:
我有一个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;
}
xml 代码:
<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>
【问题讨论】:
-
现在您只在 XAML 中而不是在代码中进行绑定。你也可以在 XAML 中设置
DataContext。 -
@AnjumSKhan 那么我应该写什么 DataContext="{Binding ...}"?
-
<Window.DataContext> <Binding RelativeSource="{RelativeSource Self}"/></Window.DataContext>,并在您的列表框中ItemsSource="{Binding ListHelmets}"。
标签: wpf list xaml binding listbox