我正在尝试将列表框的项目源绑定到 Linq 表,就像您通常将 ObservableCollection 绑定到它一样。
当项目被删除、添加和更改时,我希望我的列表与表格一起更新。
我已经在表所包含的类上实现了 INotifyPropertyChanged。这会使列表更新我的项目包含的属性,但是,为了在添加或删除项目时更新列表,我必须以编程方式重新绑定 ItemsSource 以强制更新列表。
数据上下文
public class LocalDatabase : DataContext
{
public static string connectionString = "Data Source=isostore:/Database.sdf";
public LocalDatabase() : base(connectionString) { }
public Table<Connection> Connections;
}
表对象
[Table]
public class Connection : INotifyPropertyChanged
{
private string name;
private string ip;
private ushort port;
[Column(IsPrimaryKey=true, IsDbGenerated=true)]
public int ID { get; set; }
[Column]
public string Name { get { return name; } set { name = value; NotifyPropertyChanged("Name"); } }
[Column]
public string IP { get { return ip; } set { ip = value; NotifyPropertyChanged("IP"); } }
[Column]
public ushort Port { get { return port; } set { port = value; NotifyPropertyChanged("Port"); } }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
目标清单
<ListBox Name="listBoxConnections" SelectionChanged="listBoxConnections_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Height="78">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Edit" Click="ConnectionEdit" Tag="{Binding ID}" />
<toolkit:MenuItem Header="Delete" Click="ConnectionDelete" Tag="{Binding ID}" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<StackPanel Orientation="Horizontal" Margin="12,-6,12,0">
<TextBlock Text="{Binding IP}" Style="{StaticResource PhoneTextSubtleStyle}" Margin="0" />
<TextBlock Text=":" Margin="2,0,2,0" />
<TextBlock Text="{Binding Port}" Style="{StaticResource PhoneTextSubtleStyle}" Margin="0" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
当前绑定方式
public LocalDatabase Database { get; set; }
public MainPage()
{
InitializeComponent();
Database = new LocalDatabase();
if (!Database.DatabaseExists()) Database.CreateDatabase();
listBoxConnections.ItemsSource = Database.Connections;
DataContext = this;
}
恐怕某处可能存在重复,但我一直在寻找过去 2 天,但没有找到解决方案或类似问题。可能使用了错误的查询。
所以,总而言之,我想知道将 Table 绑定到列表的正确方法,它会在删除或添加项目时更新,以及所有这些好东西。
我正在使用 Windows Phone 7.1