Pet*_*ter 2 data-binding wpf listview
我意识到这是一个很长的问题,但我发现这里没有别的办法,只能发布我的代码,为了清楚起见,我尽量保持尽可能短而简单.当然,违反了大量的最佳实践,这个例子足够长,因为它是......
我做了一个非常简单的wpf应用程序
在以下示例中,我编辑了Bar的年龄.但是,在列表中,年龄不会更新.如果我询问基础集合,它似乎仍然有更新..如何让列表知道?
以下是截图,代码和XAML
注意:如果图像未显示,请尝试在新选项卡或窗口中打开它.

namespace ASAPBinding
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return String.Format("{0} ({1})",Name,Age);
}
}
}
Run Code Online (Sandbox Code Playgroud)
namespace ASAPBinding
{
public class Dal
{
public ObservableCollection<Person> Persons { get; set; }
public Dal()
{
Persons = new ObservableCollection<Person>();
Persons.Add(new Person() {Name = "Bar", Age = 25});
Persons.Add(new Person() {Name = "Foo", Age = 50});
}
public void PrintOutCollection()
{
MessageBox.Show(
Persons[0].ToString() + "\n" + Persons[1].ToString()
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
<Window x:Class="ASAPBinding.EditPersons"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ASAPBinding"
x:Name="window1"
Title="EditPersons" Height="300" Width="300">
<Window.Resources>
<local:Dal x:Key="dal"/>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<ListBox Name="ListBox1"
ItemsSource="{Binding Source={StaticResource dal}, Path=Persons, Mode=TwoWay}"
Grid.Column="0"/>
<StackPanel
DataContext="{Binding ElementName=ListBox1, Path=SelectedItem, Mode=TwoWay}"
Grid.Column="1" Margin="0,0,0,108">
<TextBox Text="{Binding Path=Name}" />
<TextBox Text="{Binding Path=Age}" />
<Button Click="Button_Click">Show Collection</Button>
</StackPanel>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
public partial class EditPersons : Window
{
public EditPersons()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Dal dal = (Dal) window1.FindResource("dal");
dal.PrintOutCollection();
}
}
Run Code Online (Sandbox Code Playgroud)
这是不够的,有一个ObservableCollection,如果你要更新的特定属性的结合,你的人物类型必须实现INotifyPropertyChanged接口.
编辑
我刚刚注意到,你的左ListBox没有更新,因为没有为Person对象设置DataTemplate.你现在拥有的是一个ToString()实现,它在向UI报告后不会得到更新.
你需要这样的东西:
<DataTemplate DataType="{x:Type local:Person}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="("/>
<TextBlock Text="{Binding Age}"/>
<TextBlock Text=")"/>
</StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8086 次 |
| 最近记录: |