2017-09-02 61 views
0

我有3個選項組合框:編輯ComboBox打開選擇文件對話框

  • 關閉
  • 汽車
  • 選擇

offauto是正常的項目,但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; 
    } 
} 

回答

1

不能在不在列表中的組合框的項目之一組合框中選擇一個項目。因此,要完成您想要的任務,您需要將所選文件添加到項目列表中,然後選擇它。是這樣的...

  // Process dialog box 
      if (result == true) 
      { 
       myComboBox.Items.Add(selectFile.FileName); 
       myComboBox.SelectedItem = selectFile.FileName; 
      } 
+0

雖然我只是選擇所謂的「選擇」,然後它改變,你可以輸入一個空的文本框的項目。我想空的文本框充滿了'選擇文件.Filename'。 –

+0

是的。 「SelectedItem」語句完成了這一點。 – AQuirky

+0

我可能會使用這種方法,但我想避免在組合框中添加另一個選項,我想查看是否有其他答案。 –

相關問題