编辑ComboBox打开选择文件对话框
问题描述:
我有3个选项组合框:编辑ComboBox打开选择文件对话框
- 关闭
- 汽车
- 选择
off
和auto
是正常的项目,但select
改变组合框到editable
并打开Select File
对话框。
但是当我按ok时,所选文件将不会出现在使用myComboBox.Text = selectFile.FileName
的ComboBox可编辑文本框中。
如何让文本出现在文本框中?
XAML
<ComboBox x:Name="myComboBox"
Margin="0,164,14,0"
VerticalAlignment="Top"
HorizontalAlignment="Right"
Width="103"
IsTextSearchEnabled="False"
SelectionChanged="myComboBox_SelectionChanged">
<System:String>off</System:String>
<System:String>auto</System:String>
<System:String>select</System:String>
</ComboBox>
C#
private void myComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if ((string)myComboBox.SelectedItem == "select")
{
myComboBox.IsEditable = true;
// Open 'Select File'
Microsoft.Win32.OpenFileDialog selectFile = new Microsoft.Win32.OpenFileDialog();
selectFile.RestoreDirectory = true;
Nullable<bool> result = selectFile.ShowDialog();
// Process dialog box
if (result == true)
{
myComboBox.Text = selectFile.FileName;
}
}
else if ((string)myComboBox.SelectedItem != "select"
&& !string.IsNullOrEmpty((string)myComboBox.SelectedItem))
{
myComboBox.IsEditable = false;
}
}
答
不能在不在列表中的组合框的项目之一组合框中选择一个项目。因此,要完成您想要的任务,您需要将所选文件添加到项目列表中,然后选择它。是这样的...
// Process dialog box
if (result == true)
{
myComboBox.Items.Add(selectFile.FileName);
myComboBox.SelectedItem = selectFile.FileName;
}
虽然我只是选择所谓的“选择”,然后它改变,你可以输入一个空的文本框的项目。我想空的文本框充满了'选择文件.Filename'。 –
是的。 “SelectedItem”语句完成了这一点。 – AQuirky
我可能会使用这种方法,但我想避免在组合框中添加另一个选项,我想查看是否有其他答案。 –