我有一個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();
我試圖把調試語句中綁定。該參數被綁定到,但值綁定永遠不會被調用。
有關如何讓我的列表顯示的任何想法?
檢查調試輸出窗口以查看是否存在任何綁定問題。我想知道你是否需要{Binding Path = xxx}而不是{Binding xxx}。 – 2010-01-09 18:55:48
如果您只指定一個參數,則不需要添加「Path =」..? – stiank81 2010-01-09 18:58:48
感謝這兩個答案。我會解決的兩個好點。 – Vaccano 2010-01-09 22:24:06