因为要加入上传图片按钮,所以将page.xaml内容修改如下:
<Grid x:Name="LayoutRoot" Background="Black" ShowGridLines="False" Margin="8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="196" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="48" />
</Grid.RowDefinitions>
<ListBox x:Name="myList" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
ItemsSource="{Binding}"
Grid.Row="0"
Grid.Column="0"
Grid.RowSpan="2"
SelectionChanged="OnSelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<my:GridSplitter Width="1" HorizontalAlignment="Left" VerticalAlignment="Stretch" Grid.Column="1"></my:GridSplitter>
<Image x:Name="myImage" Grid.Column="1" />
<StackPanel Grid.Row="1" Background="white" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Stretch">
<Button Grid.Row="1"
Grid.Column="0"
Content="选择图片"
Margin="8" Click="OnClick" FontSize="16" Width="100"/>
<Button Grid.Row="1"
Grid.Column="2"
Content="上传该图片"
Margin="8" Click="OnUpLoadClick" FontSize="16" Width="100"/>
</StackPanel>
</Grid>
而相应的page.xmal.cs代码也做了修改(相关内容见注释):
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
void OnClick(object sender, EventArgs args)
{
OpenFileDialog openFileDialog = new OpenFileDialog()
{
Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
Multiselect = true
};
if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
{
myList.DataContext = openFileDialog.SelectedFiles;
}
}
void OnUpLoadClick(object sender, EventArgs args)
{
if (fi != null)
{
WebClient webclient = new WebClient();
webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
webclient.OpenWriteAsync(new Uri("http://localhost:5840/UploadFileWeb/Handler.ashx", UriKind.Absolute), "POST", fi.OpenRead());
}
else
{
HtmlPage.Window.Alert("请选取相应图片!!!");
}
}
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
//将图片数据流发送到服务器上
Stream inputStream = e.UserState as Stream;
Stream outputStream = e.Result;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
outputStream.Close();
inputStream.Close(); HtmlPage.Window.Alert("图片上传成功!!!");
}
FileDialogFileInfo fi ; //获取选定图片信息
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if ((e.AddedItems != null) && (e.AddedItems.Count > 0))
{
fi = e.AddedItems[0] as FileDialogFileInfo;
if (fi != null)
{
using (Stream stream = fi.OpenRead())
{
BitmapImage image = new BitmapImage();
image.SetSource(stream);
myImage.Source = image;
myImage.Visibility = Visibility.Visible;
stream.Close();
}
}
}
}
}