WPF,这个绑定为什么没有效果
<Window x:Class="WPF熊俊.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Name="window1" Height="399.259" Width="604.074">
<Grid HorizontalAlignment="Left" Height="319" VerticalAlignment="Top" Width="517">
<ListBox ItemsSource="{Binding ElementName=window1, Path=ListPerson}" DisplayMemberPath="Name" HorizontalAlignment="Left" Height="160" Margin="40,41,0,0" VerticalAlignment="Top" Width="108"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ListPerson = new List<Person>()
{
new Person(){Name="张三",Adress="南街"},
new Person(){Name="李四",Adress="北京"},
new Person(){Name="王二",Adress="上海"},
};
}
private List<Person> listperson;
public List<Person> ListPerson
{
get { return listperson; }
set { listperson = value; }
}
}
public class Person
{
public string Name { get; set; }
public string Adress { get; set; }
}
[解决办法]
因为你写的绑定是在 InitializeComponent()时候执行的,这时候ListPerson为空,所以没有显示任何数据。
把初始化顺序换下就可以了:
ListPerson = new List<Person>() { 。。。 };
InitializeComponent();
或者把ListPerson做成DependencyProperty,这样ListPerson变了以后才能通知ui作出反应。
[解决办法]
<Window x:Class="WPF熊俊.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Name="window1" Height="399.259" Width="604.074">
<Grid HorizontalAlignment="Left" Height="319" VerticalAlignment="Top" Width="517">
<ListBox ItemsSource="{Binding ElementName=window1, Path=ListPerson}" DisplayMemberPath="Name" HorizontalAlignment="Left" Height="160" Margin="40,41,0,0" VerticalAlignment="Top" Width="108"/>
</Grid>
</Window>
using System.Collections.Generic;
using System.Windows;
namespace WPF熊俊
{
public partial class MainWindow : Window
{
public MainWindow()
{
ListPerson = new List<Person>()
{
new Person() {Name = "张三", Adress = "南街"},
new Person() {Name = "李四", Adress = "北京"},
new Person() {Name = "王二", Adress = "上海"},
};
InitializeComponent();
}
private List<Person> listperson;
public List<Person> ListPerson
{
get { return listperson; }
set { listperson = value; }
}
}
public class Person
{
public string Name { get; set; }
public string Adress { get; set; }
}
}
private DependencyProperty ListPersonProperty;
public Window1()
{
ListPersonProperty = DependencyProperty.Register("ListPerson", typeof(List<Person>), typeof(Window1), new PropertyMetadata());
InitializeComponent();
this.ListPerson = new List<Person>() { new Person() { Name = "dasdada" } };
}
public List<Person> ListPerson
{
get { return (List<Person>)GetValue(ListPersonProperty); }
set
{
SetValue(ListPersonProperty, value);
}
}
}
public class Person
{
public string Name { get; set; }
}