根据ListBox选择更改标签内容

时间:2012-03-13 14:23:49

标签: c# wpf xaml data-binding

我有一个绑定到ObservableCollection的ListBox:

<ListBox Name="ListBoxItemsList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Margin="0" FlowDirection="RightToLeft">
                <Button Content="Add me!" Click="AddItem" />
                <TextBlock Text="{Binding Path=name}" />
                <TextBlock Text="{Binding Path=description}"  />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ObservableCollection对象有几个属性,包括uniqueIDnamedescriptioncolourflavour。根据ListBox中选定的项目,我想使用所选项目的属性填充一些标签。此外,每个项目的Button应该执行一个独特的操作(即将一个相关的项添加到数组)但是我无法弄清楚如何向AddItem()方法发送一个唯一的参数。我认为这将是一个常见的用例,但我通过谷歌搜索找不到任何东西。

感谢。

1 个答案:

答案 0 :(得分:1)

  

根据ListBox中的选定项目,我想了解详细信息   一些标签显示所选项目的属性

您可以将ListBox.SelectedItem绑定到DependencyProperty,然后将该属性绑定到这些标签。

  

此外,每个项目的按钮应执行独特的操作(即   将一个相关项添加到数组中但是我无法弄清楚   如何向AddItem()方法发送唯一参数。

您可以将Item ID添加到Button.Tag

<Button Content="Add me!" Click="AddItem" Tag={Binding Path=id} />

然后只需获取发件人的按钮标记

public void button_clicked(object sender, event e) {
    int id = ((Button)sender).Tag as Int32;
    ...
}

编辑:您还可以将完整的项目而不仅仅是ID绑定到按钮标记。

相关问题