这是我的第一个UWP应用程序,我确信我只是遗漏了一些非常简单的东西。
我正在尝试构建一个openfilepicker,允许用户通过列表框选择要包含的文件类型(.JPEG,.BMP等)。我的问题是我的列表框返回的值无效。返回的值是“my solution name.page name.Classname”,而不是用户在列表框中选择的值(例如.JPEG“)。
XAML:
<ListBox x:Name="lstPhotoType" Height="197" SelectionMode="Multiple" FontSize="12" VerticalAlignment="Top" Background="{x:Null}" SelectionChanged="lstPhotoType_SelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Top">
<TextBlock x:Name="pictureType" Text="{Binding pType, Mode=TwoWay}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" FontWeight="Bold" FontSize="12"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的c#代码:
//Start creating the fileopenpicker.
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
//Count the number of selected photos files.
int count = lstPhotoType.SelectedItems.Count();
//If 1 of more photo type/s has been selected - build openpicker filetypefilter.
if (count > 0)
{
foreach (object listBoxItem in lstPhotoType.SelectedItems)
{
// string value = Convert.ToString(listBoxItem);
fileOpenPicker.FileTypeFilter.Add(listBoxItem.ToString());
}
}
任何建议都将不胜感激。
编辑1
我的PictureTypes类代码
public class PictureTypes
{
public string pType { get; set; }
}
string[] arrayoftypes = new string[5] { "*All", ".BMP", ".JPEG", ".JPG", ".PNG"};
public void makePictureTypeList()
{
for (int i = 0; i < 5; i++)
{
//Create a new instace of the PictureTypes class
PictureTypes obj = new PictureTypes();
//build array of data
obj.pType = arrayoftypes[i];
//Add the the picture types into the listbox
lstPhotoType.Items.Add(obj);
}
}
答案 0 :(得分:0)
尝试此操作:获取所选项目值。
string text = listBoxItem.GetItemText(listBoxItem.SelectedItem);
修改强>
尝试以下方法 这应该有效:
int index;
string item;
foreach (int i in lstPhotoType.SelectedIndices)
{
index = lstPhotoType.SelectedIndex;
item = lstPhotoType.Items[i].ToString ();
MessageBox.Show(item);
}
答案 1 :(得分:0)
您应该能够将SelectedItems集合中的项目转换为定义了“pType”属性的类型,并直接访问此属性:
if (count > 0)
{
foreach (PictureTypes listBoxItem in lstPhotoType.SelectedItems.OfType<PictureTypes>())
{
fileOpenPicker.FileTypeFilter.Add(listBoxItem.pType);
}
}
或者您可以使用动态类型:
if (count > 0)
{
foreach (dynamic listBoxItem in lstPhotoType.SelectedItems)
{
fileOpenPicker.FileTypeFilter.Add(listBoxItem.pType);
}
}
感谢mm8,但调试仍然将pType显示为“我的解决方案名称.page name.Classname
在这种情况下,“调试”是什么意思?这将为您提供当前选择的字符串值:
private void lstPhotoType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int count = lstPhotoType.SelectedItems.Count();
if (count > 0)
{
foreach (PictureTypes listBoxItem in lstPhotoType.SelectedItems.OfType<PictureTypes>())
{
string value = listBoxItem.pType; //<- value = ".BMP" or ".JPG", etc.
}
}
}