0

这是我的xml:

<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>

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

4

1 回答 1

0

如果我没看错,你不需要做任何特别的事情来访问 DataTemplate 中的 TextBlock 控件。您只需要通过使用 TwoWay 绑定将 SelectedItem 绑定添加到您的 ListBox 来利用您的绑定。

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

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

于 2012-05-22T16:52:11.633 回答