Reputation: 567
This question is a follow-up to one I asked and got answered here: How to display XPS document using a selected combobox item
I've created a WPF app using VB 2010. I set the comboboxitems via the XAML. However, I can't seem to figure out how to set the value of each item to a file path.
The objective is for a user to be able to select an item from a drop-down list, then that selection opens an XPS file in the DocumentViewer. The code below was provided to me by COMPETENT_TECH (thanks) to read and display the value of the selected comboboxitem in the DocumentViewer.
The path to the files I want opened is C:\folder\file.xps
Private Sub Button4_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button4.Click
Try
Dim sFileName As String
sFileName = DirectCast(ComboBox1.SelectedValue, String)
If Not String.IsNullOrEmpty(sFileName) Then
Dim theDocument As New System.Windows.Xps.Packaging.XpsDocument(sFileName, System.IO.FileAccess.Read)
DocumentViewer1.Document = theDocument.GetFixedDocumentSequence()
End If
Catch ex As Exception
MessageBox.Show("ERROR: " & ex.Message)
End Try
End Sub
Thanks in advance for your assistance.
Update
Here's the XAML I'm using:
<ComboBox Width="Auto" IsReadOnly="True" IsEditable="True" Name="ComboBox1" Height="Auto" Margin="0" Padding="1" Grid.Column="2">
<ComboBoxItem>123456</ComboBoxItem>
<ComboBoxItem>123457</ComboBoxItem>
<ComboBoxItem>123458</ComboBoxItem>
</ComboBox>
Upvotes: 1
Views: 215
Reputation: 30830
I highly recommend you use Data Binding with that ComboBox.
create a class something like following:
Class XPSDocumentInfo
{
Public Property Title As String
Public Property FileName As String
}
Create an ObservableCollection(Of XPSDocumentInfo)
and bind it to ComboBox's ItemsSource.
Use DisplayMemberPath="Title"
attribute on ComboBox so that it will use Title property to show text in dropdown but since you bound collection of type XPSDocumentInfo, SelectedItem property of that ComboBox with return an object of type XPSDocumentInfo.
For example,
sFileName = DirectCast(ComboBox1.SelectedValue, String)
will be changed to
sFileName = DirectCast(ComboBox1.SelectedItem, XPSDocumentInfo).FileName
Upvotes: 0
Reputation: 44931
Depending on precisely how the xaml to load the combobox is specified, you will probably want to change this line:
Dim theDocument As New System.Windows.Xps.Packaging.XpsDocument(sFileName, System.IO.FileAccess.Read)
to:
Dim theDocument As New System.Windows.Xps.Packaging.XpsDocument(System.IO.Path.Combine("C:\folder", sFileName & ".xps"), System.IO.FileAccess.Read)
All that we do in the new code is combine the directory where the files are stored with the file name retrieved from the combobox.
Update
The correct way to retrieve the value from the combobox is:
If ComboBox1.SelectedValue IsNot Nothing Then
sFileName = DirectCast(ComboBox1.SelectedValue, ComboBoxItem).Content.ToString()
End If
Upvotes: 1