2012-10-24 51 views
1

我已經定義如下監視列表:WPF組合框忽略的ToString覆蓋對象

// a named list of VariableWatchers 
public class WatchList : List<VariableWatcher> 
{ 
    private string _name; 

    public WatchList(string name) : base() 
    { 
     _name = name; 
    } 

    public override string ToString() 
    { 
     return _name; 
    } 
} 

我必將監視列表的組合框的ItemsSource屬性的列表如下:

<ComboBox x:Name="WatchListDropdown" 
      ItemsSource="{Binding Path=WatchLists}" 
      VerticalAlignment="Center" 
      Margin="5"/> 

「觀察列表「是指我的DataContext中的以下屬性:

public IList<WatchList> WatchLists 
{ 
    get { return _watchLists; } 
} 

一切正常工作很好excep t列表中的所有條目都顯示爲「(Collection)」而不是_name變量。我在ToString中放置了一個斷點,並確認它在某個時刻被調用,並返回了正確的值,但不知何故,ComboBox仍然顯示「(Collection)」。

回答

4

不知道爲什麼它不使用ToString()重寫,但是您是否考慮過使用DisplayMemberPath?

<ComboBox x:Name="WatchListDropdown" 
     ItemsSource="{Binding Path=WatchLists}" 
     VerticalAlignment="Center" 
     DisplayMemberPath="Name" 
     Margin="5"/> 

當然,您將需要調整您的對象,因爲綁定需要公共屬性或依賴屬性。

private string _name; 
public string Name { get { return _name; } set { _name = value; } } 
+0

謝謝,工作!我也很困惑,爲什麼它不使用ToString,因爲之前一直對我有用。 – hypehuman

0

WatchLists是WatchList的集合是不是?所以Collection.ToString()將被調用並顯示。

如何將DisplayMemberPath指定爲「名稱」?我希望它能起作用:)

0

如果ItemsSource綁定到一個WatchList,其類型爲List<VariableWatcher>,則顯示的實際集合將是列表VariableWatcher

如果ItemsSource綁定到WatchList的集合,則.ToString()應覆蓋默認顯示。當然,您可以隨時創建一個屬性Name並製作DisplayMember。