2010-01-09 85 views
0

我有一個ObservableCollection,我似乎無法在窗口中顯示。下面是代碼:WPF - 無法在窗口中顯示ObservableCollection

視圖模型:

public class QueryParamsVM : DependencyObject 
{ 
    public string Query { get; set; } 

    public QueryParamsVM() 
    { 
     Parameters = new ObservableCollection<StringPair>(); 
    } 

    public ObservableCollection<StringPair> Parameters 
    { 
     get { return (ObservableCollection<StringPair>)GetValue(ParametersProperty); } 
     set { SetValue(ParametersProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Parameters. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty ParametersProperty = 
     DependencyProperty.Register("Parameters", typeof(ObservableCollection<StringPair>), typeof(QueryParamsVM), new UIPropertyMetadata(null)); 
} 


public class StringPair: INotifyPropertyChanged 
{ 
    public string Key { get; set; } 
    public string Value 
    { 
     get { return _value; } 
     set { _value = value; OnPropertyChanged("IsVisible"); } 
    } 
    private string _value; 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

的窗口XAML:

<Window x:Class="WIAssistant.QueryParams" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Query Parameters" Height="390" Width="504"> 

    <Grid> 
     <ListBox DataContext="{Binding Parameters}" > 

      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel> 
         <TextBlock Text="{Binding Key}" ></TextBlock> 
         <TextBlock Text="{Binding Value}"></TextBlock> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox>   
    </Grid> 
</Window> 

調用代碼:

// Get Project Parameters 
QueryParams queryParams = new QueryParams(); 
queryParams.ViewModel.Parameters.Add(new StringPair {Key = "@project", Value = ""}); 
queryParams.ShowDialog(); 

我試圖把調試語句中綁定。該參數被綁定到,但值綁定永遠不會被調用。

有關如何讓我的列表顯示的任何想法?

+0

檢查調試輸出窗口以查看是否存在任何綁定問題。我想知道你是否需要{Binding Path = xxx}而不是{Binding xxx}。 – 2010-01-09 18:55:48

+1

如果您只指定一個參數,則不需要添加「Path =」..? – stiank81 2010-01-09 18:58:48

+0

感謝這兩個答案。我會解決的兩個好點。 – Vaccano 2010-01-09 22:24:06

回答

3

嘗試

<ListBox ItemsSource="{Binding Parameters}"> 

<ListBox DataContext="{Binding Parameters}" ItemsSource="{Binding}"> 
+0

謝謝。這是問題所在。 – Vaccano 2010-01-09 22:21:19

1

一個奇怪的位置:

public string Value 
{ 
    get { return _value; } 
    set { _value = value; OnPropertyChanged("IsVisible"); } 
} 

你在一個不同的屬性提升一個屬性更改事件。應該可能是:

public string Value 
{ 
    get { return _value; } 
    set { _value = value; OnPropertyChanged("Value"); } 
} 
+0

好點。我會解決這個問題(這是複製和粘貼的危險)。然而這個問題是由於斯坦尼斯拉夫指出的。 – Vaccano 2010-01-09 22:23:21