WPF - 无法在窗口中显示ObservableCollection
问题描述:
我有一个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();
我试图把调试语句中绑定。该参数被绑定到,但值绑定永远不会被调用。
有关如何让我的列表显示的任何想法?
答
尝试
<ListBox ItemsSource="{Binding Parameters}">
或
<ListBox DataContext="{Binding Parameters}" ItemsSource="{Binding}">
+0
谢谢。这是问题所在。 – Vaccano 2010-01-09 22:21:19
答
一个奇怪的位置:
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
检查调试输出窗口以查看是否存在任何绑定问题。我想知道你是否需要{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