datatemplate列表框选中的项目

时间:2012-05-22 15:37:40

标签: wpf

这是我的xaml:

<Window x:Class="WpfTest.Search"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Search" Height="600" Width="1024">

    <Window.Resources>
        <DataTemplate x:Key="listBoxTemplate" xmlns:ns="clr-namespace:MyConverters">
            <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <ns:ImageConverter x:Key="MyImageConverter" />
                </StackPanel.Resources>
                <Image Source="{Binding Path=thumb, StringFormat=/WpfTest;component/Images/{0}, Converter={StaticResource MyImageConverter}}" Height="100" Width="130" Margin="5"></Image>
                <StackPanel Orientation="Vertical" Width="247">
                    <TextBlock Text="{Binding recipeName}" Height="60" Padding="15" FontSize="16" HorizontalAlignment="Stretch" VerticalAlignment="Center"></TextBlock>
                    <TextBlock Text="{Binding cuisine}" Height="60" Padding="15" FontSize="16" HorizontalAlignment="Stretch" VerticalAlignment="Center"></TextBlock>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ListBox Margin="12,96,0,0" Name="lstSearchResult" HorizontalAlignment="Left"
                 VerticalAlignment="Top" Width="704" Height="445" ItemsSource="{Binding Tables[0]}" ItemTemplate="{StaticResource listBoxTemplate}" SelectionChanged="lstSearchResult_SelectionChanged">
        </ListBox>
        <TextBox Height="31" HorizontalAlignment="Left" Margin="12,49,0,0" Name="txtSearchRecipe" VerticalAlignment="Top" Width="518" FontSize="16" />
        <Button Content="Search" Height="31" HorizontalAlignment="Left" Margin="555,49,0,0" Name="btnSearchRecipe" VerticalAlignment="Top" Width="161" Click="btnSearchRecipe_Click" />
    </Grid>
</Window>

现在我想根据我在列表框中单击的项目打开一个新表单,将新表单传递给所选项目的文本块中的数据。我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果我正确读取此内容,则无需执行任何特殊操作即可访问DataTemplate中的TextBlock控件。您只需要通过使用TwoWay绑定向ListBox添加SelectedItem绑定来利用绑定。

如果您正在使用MVVM,我建议您将按钮单击事件上的命令映射到View Model,并将SelectedItem作为命令参数传递。然后,在命令处理程序中,将SelectedItem强制转换为您期望的类型(这应该是您绑定到ListBox ItemsSource的集合中的对象类型)。然后,您可以将绑定到TextBlocks的属性发送到新窗口的视图模型。如果设置属性,这些项应该存在于SelectedItem中。然后将窗口的DataContext设置为相应的窗口视图模型并显示它。

如果您只是使用后面的代码,只需将SelectedItem强制转换为ListBox ItemsSource集合中使用的类型。然后将绑定到TextBlocks的属性传递给新窗口。然后显示窗口。