2014-02-18 64 views
0

我創建的ObservableCollection:的ObservableCollection綁定到一個ComboBox

public ObservableCollection<Tool> toolList = new ObservableCollection<Tool>(); 

而且我設置的DataContext在構造函數中:

public MainWindow() 
    {   
     InitializeComponent(); 
     DataContext = toolList;   
    } 

實際:

public MainWindow() 
    { 

     InitializeComponent(); 
     DataContext = this; 

    } 

清單市民:

public ObservableCollection<Tool> ToolList 
    { 
     get { return toolList; } 
    } 

如何我的對象添加到列表:

private void buttonAdd_Click(object sender, RoutedEventArgs e) 
    { 
     InputDialog input = new InputDialog(); 
     input.ShowDialog(); 
     inputNewTool = input.enteredTxt; 

     if (inputNewTool != null) 
     { 
      System.Windows.Forms.MessageBox.Show("Chose the Tool's directory"); 
      dlg.DefaultExt = ".exe"; 
      dlg.Filter = "Application (.exe)|*.exe"; 

      if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       Tool tool = new Tool(); 
       tool.Name = inputNewTool; 
       tool.Path = dlg.FileName; 
       toolList.Add(tool); 
      }     
     }    
    } 

我想,只有Toolobject的名字顯示在下拉框中。 XAML:

<ComboBox ItemsSource="{Binding Path= ToolList}" DisplayMemberPath="Name" 
SelectedValuePath ="Name" SelectedValue="{Binding Path=ToolList}" Height="22" 
Name="comboBoxTools" Width="185" IsEditable="False" /> 

編輯:現在的XAML顯示如此:

<ComboBox ItemsSource="{Binding Path= ToolList, 
    UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" 

Toolclass:

public class Tool 
{ 
    public string Name { get; set; } 
    public string Path { get; set; } 

    public Tool() { } 
} 

我什麼也看不到在ComboBox。爲什麼?這些工具已成功添加到Collection中。 我生氣

+1

你'SelectedValue'被綁定到作爲你的'ItemsSource'相同的路徑。這似乎很腥。 – nvoigt

+0

我刪除選定的值和選定的路徑,但這不會解決問題:/ – LittleProgrammer

回答

3

您已設置的DataContext窗口來ObservableCollection本身。

所以要麼綁定ItemsSource與DataContext本身因爲Binding會自動指向List實例。

<ComboBox ItemsSource="{Binding}"/> 

OR

最好你應該設置的DataContext本身:

DataContext = this; 

此外,SelectedValue指向只列出。這沒有任何意義。如果不使用SelectedValuePath,它應指向類Tool的實例。並且在使用SelectedValuePath的情況下,它應該指向字符串類型的屬性。

請將其完全移除或將其設置爲正確的實例。

+0

他不會得到第一個提議的解決方案,因爲他對SelectedValue的綁定也是錯誤的。你的第二種方法是正確的,將'DataContext'設置爲'this'並將'SelectedValue'改爲另一個屬性(我們還不知道)。 – Herm

+0

@Herm - 首先他會獲得組合框中的項目。 「SelectedValue」部分適用於這兩種解決方案,而不是針對第二種解決方案。 –

+0

是的,只是想提到第一次綁定(將DataContext設置爲列表),將SelectedValue綁定到MainWindow的另一個屬性會很麻煩,這在第二個解決方案中確實更容易。當然,第一個會正確填充列表。 – Herm

0

嘗試設置UpdateSourceTriggerPropertyChanged在你的ItemsSource-綁定

+0

沒有任何改變: LittleProgrammer

0

好吧我在YouTube上找到了一個簡單的解決方案(數據綁定與Windows Presenation基金會從ht195367)。我沒有在Xaml中定義comboBox.ItemsSource,而是在Window_Loaded中定義。

comboBoxTools.ItemsSource = toolList; 

對於表演我的工具類實現ToStringng工具的名稱:

public override string ToString() 
{ 
     return Name; 

} 
+1

通過這種方法,您可以回到傳統的Winforms方法,而無需使用任何WPF綁定引擎的優勢。祝你有美好的一天..!! :) –

相關問題