在WPF / C#中以新窗口传递图像

时间:2015-02-05 09:27:29

标签: c# wpf listbox

我在ListBox中有一些图像。当用户单击一个图像时,我想打开一个新窗口(ImageWindow)并在新窗口中显示单击的图像。我已经添加了一个新的XAML文件和一个事件处理程序。这就是我得到的:

主窗口:

<ListBox Name="MainListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <DockPanel HorizontalAlignment="Center">
                <Image Source="{Binding}" MouseDown="Image_MouseDown"></Image>
            </DockPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

/*========================================================================*/

private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
    ImageWindow imageWindow = new ImageWindow();
    //Pass image
    imageWindow.Show();
}

ImageWindow:

<ListBox Name="ImageListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <DockPanel HorizontalAlignment="Center">
                <Image Source="{Binding}"></Image>
            </DockPanel>
        </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

如何传递点击的图片?

请参阅example(点击图片)

2 个答案:

答案 0 :(得分:1)

只需复制,过去并调整此代码,使其适合您的varnames:

private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) //Varname
    {

        ImageWindow imageWindow = new ImageWindow { Owner = this };
        foreach (var item in ListBox.Items) //Varname
        {
            imageWindow.ListBox.Items.Add(item);//Varname
        }

        imageWindow.SetSelectedImageIndex = ListBox.SelectedIndex; //Varname + save the index of the selected item and pass it to ImageWindow
        imageWindow.Show();
    }

ImageWindow:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Application.Current.MainWindow.WindowState = WindowState.Normal;
    ListBoxItem lbi = (ListBoxItem)ImageListBox.ItemContainerGenerator.ContainerFromIndex(SetSelectedImageIndex); //Get with the index the befor selected item
    lbi.Focus(); //Set the focus on it
}

答案 1 :(得分:0)

你可以从这样的事情开始:

<Grid 
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">

    <Popup x:Name="popup" PlacementTarget="{Binding ElementName=imageList}">
        <Image Source="{Binding PlacementTarget.SelectedItem , ElementName=popup}"/>
    </Popup>
    <ListView x:Name="imageList" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <ei:ChangePropertyAction PropertyName="IsOpen" 
                    TargetName="{Binding ElementName=popup}" Value="True"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ListView>
</Grid>

添加对 Microsoft.Expression.Interactions System.Windows.Interactivity 的引用,以使其正常工作。