datatemplate和绑定

时间:2012-12-08 11:25:57

标签: xaml

如果从dataTemplate到达listBoxItem以显示标签中的选定项目,我如何使用listBox中的Binding

这是我的代码:

<Window.Resources>
    <XmlDataProvider x:Key="data">
        <x:XData>
            <colors xmlns="">
                <color name="yellow"/>
                <color name="red"/>
                <color name="blue"/>
                <color name="black"/>
                <color name="pink"/>
                <color name="brown"/>
                </colors>
        </x:XData>
    </XmlDataProvider>

    <DataTemplate x:Key="temp">
        <StackPanel Orientation="Vertical">
            <Label Content="{Binding XPath=@name}"/>
        </StackPanel>
    </DataTemplate>



</Window.Resources>
<StackPanel Orientation="Vertical">

    <ListBox Name="lblColor" ItemsSource="{Binding Source={StaticResource data}, XPath=colors/color}"
             ItemTemplate="{StaticResource temp}" Background="Transparent" SelectedIndex="0"></ListBox>
    <Label Content="your choice is :"></Label>

    <Label ></Label>


</StackPanel>

我想在最后一个标签的内容中显示所选项目... 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

 <ListBox x:Name="lblColor" ItemsSource="{Binding Source={StaticResource data}, XPath=colors/color}"
         ItemTemplate="{StaticResource temp}" Background="Transparent" SelectedIndex="0" SelectedValuePath="@name" ></ListBox>
    <Label Content="your choice is :"></Label>

    <Label Content="{Binding ElementName=lblColor,Path=SelectedValue}"   />