如何编辑绑定到可观察集合的列表框中的数据以及来自隔离存储数据库的数据
本文关键字:数据 数据库 存储 隔离 列表 编辑 绑定 集合 观察 何编辑 | 更新日期: 2023-09-27 18:06:15
我正在研究如何编辑数据,当用户首先插入他的姓名,年龄和地址,数据显示在windows phone的另一页上,现在用户想要编辑绑定到observablecollection的列表框的项目,我想编辑和更新数据库中的数据,以及列表得到刷新。请帮帮我吧
这是我的代码的数据库,我添加,删除和编辑
public class SampleData
{
//Define Method for add a baby detail
public bool AddSample(Sample sample)
{
try
{
using (SqliteSampleDataContext sampleDataContext = new SqliteSampleDataContext(SqliteSampleDataContext.DBConnectionString))
{
SqliteSampleTable sampleDetail = new SqliteSampleTable();
sampleDetail.Name = sample.Name;
sampleDataContext.Sample.InsertOnSubmit(sampleDetail);
sampleDataContext.SubmitChanges();
return true;
}
}
catch
{
return false;
}
}
//Define Method for delete a baby detail
public bool DeleteSample(int id)
{
try
{
using (SqliteSampleDataContext sampleDataContext = new SqliteSampleDataContext(SqliteSampleDataContext.DBConnectionString))
{
//Delete Baby object
var sampleObj = (from item in sampleDataContext.Sample where item.Id == id select item).FirstOrDefault();
sampleDataContext.Sample.DeleteOnSubmit(sampleObj);
//babyCareDataContext.SubmitChanges();
sampleDataContext.SubmitChanges();
return true;
}
}
catch
{
return false;
}
}
这是我的视图模型
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
private ObservableCollection<Sample> _itemsList;
public ObservableCollection<Sample> ItemsList
{
get
{
return _itemsList;
}
set
{
_itemsList = value;
NotifyPropertyChanged("ItemsList");
}
}
public MainViewModel()
{
ItemsList = new ObservableCollection<Sample>();
GetSampleList();
}
//Define Method for get baby list
public void GetSampleList()
{
try
{
SqliteSampleDataContext sampleDataContext = new SqliteSampleDataContext(SqliteSampleDataContext.DBConnectionString);
if (sampleDataContext.Sample.Count() > 0)
{
this.ItemsList.Clear();
SampleData objSampleData = new SampleData();
List<SqliteSampleTable> samples = objSampleData.GetSamples();
foreach (var item in samples)
{
this.ItemsList.Add(new Sample
{
Name = item.Name,
Id = item.Id
});
}
}
else
this.ItemsList.Clear();
}
catch
{
}
}
public void SaveSampleDetail(Sample sample)
{
SampleData objBabyData = new SampleData();
objBabyData.AddSample(sample);
App.ViewModel.GetSampleList();
}
}
}
这是一个以UI为中心的问题,它只是取决于你想如何处理它。为了给用户提供最好的用户体验,在我看来,最好将用户重定向到详细信息视图页面。
如果您必须在列表中编辑用户详细信息,您可能会采用这种方法。
- 确保你的模型属性实现INotifyPropertyChanged接口
- 创建两个转换器,可以将UI控件的可见性设置为可见或折叠状态 在你的业务逻辑和你的UI代码。
在这个例子中,我使用的是mmvmlight框架,你可以很容易地将它适应你使用的任何框架。
您的转换器,请注意,如果您愿意,您可以将其卷成一个转换器,只需传入true或false的命令参数,然后实现正确的逻辑。我决定保持事情简单
public class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool visible;
bool.TryParse(value.ToString(), out visible);
return visible ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class VisibilityInvertedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool visible;
bool.TryParse(value.ToString(), out visible);
return visible ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
用户实体 public class UserInfomation : ObservableObject
{
#region Properties and Fields
private string firstName;
private string lastName;
private string addressLineOne;
private bool editMode;
#endregion
#region Public Properties
public string FirstName
{
get { return this.firstName; }
set
{
if (this.firstName != value)
{
this.firstName = value;
this.RaisePropertyChanged();
}
}
}
public string LastName
{
get { return this.lastName; }
set
{
if (this.lastName != value)
{
this.lastName = value;
this.RaisePropertyChanged();
}
}
}
public string AddressLineOne
{
get { return this.addressLineOne; }
set
{
if (this.addressLineOne != value)
{
this.addressLineOne = value;
this.RaisePropertyChanged();
}
}
}
public bool EditMode
{
get { return this.editMode; }
set
{
if (this.editMode != value)
{
this.editMode = value;
this.RaisePropertyChanged();
}
}
}
#endregion
}
你的viewModel应该看起来类似于:
public class MainViewModel : ViewModelBase
{
#region Properties and Fields
/// <summary>
/// A collection of user records.
/// </summary>
private ObservableCollection<UserInfomation> users;
/// <summary>
/// Command to execute when a record is to be edited.
/// </summary>
public RelayCommand<UserInfomation> EditUserDetail { get; private set; }
/// <summary>
/// Command to execute when a record is to be saved.
/// </summary>
public RelayCommand<UserInfomation> SaveUserDetail { get; private set; }
/// <summary>
/// Holds the current data that is being edited, if any.
/// </summary>
private UserInfomation userDataInEditMode;
#endregion
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
this.EditUserDetail = new RelayCommand<UserInfomation>(EditUserDetailAction);
this.SaveUserDetail = new RelayCommand<UserInfomation>(SaveUserDetailAction);
this.GenerateData();
}
#region Public Properties
public ObservableCollection<UserInfomation> Users
{
get { return this.users; }
set
{
if (this.users != value)
{
this.users = value;
this.RaisePropertyChanged();
}
}
}
#endregion
#region Methods
private void GenerateData()
{
this.Users = new ObservableCollection<UserInfomation>
{
new UserInfomation { FirstName = "John", LastName = "Smith", AddressLineOne = "1 John Avenue, Florida" },
new UserInfomation { FirstName = "Peter", LastName = "Wandsworth", AddressLineOne = "34 Peter Avenue, Denver" },
new UserInfomation { FirstName = "Emily", LastName = "Stone", AddressLineOne = "1 Emily Avenue, London" }
};
}
private void EditUserDetailAction(UserInfomation userDataToEdit)
{
if (userDataInEditMode != null)
{
this.userDataInEditMode.EditMode = false;
}
this.userDataInEditMode = userDataToEdit;
this.userDataInEditMode.EditMode = true;
}
private void SaveUserDetailAction(UserInfomation userDataToSave)
{
//Save your data here:
if (userDataInEditMode != null)
{
userDataInEditMode.EditMode = false;
MessageBox.Show("first name changed to " + userDataToSave.FirstName);
}
}
#endregion
}
最后你的UI代码
<phone:PhoneApplicationPage
x:Class="TestApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModel="clr-namespace:TestApp.ViewModel"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
x:Name="ApplicationPage"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<phone:PhoneApplicationPage.Resources>
<viewModel:VisibilityConverter x:Key="RowVisibilityConverter" />
<viewModel:VisibilityInvertedConverter x:Key="RowVisibilityInvertedConverter" />
</phone:PhoneApplicationPage.Resources>
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox ItemsSource="{Binding Users}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Border Visibility="{Binding EditMode, Converter={StaticResource RowVisibilityInvertedConverter}}" Width="450" Margin="0 0 0 20" Padding="15" BorderThickness="2" BorderBrush="{StaticResource PhoneAccentBrush}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="First name" FontSize="{StaticResource PhoneFontSizeMediumLarge}" />
<TextBlock Grid.Row="1" Text="{Binding FirstName}" Foreground="{StaticResource PhoneAccentBrush}" />
<TextBlock Grid.Row="2" Text="Last name" FontSize="{StaticResource PhoneFontSizeMediumLarge}" />
<TextBlock Grid.Row="3" Text="{Binding LastName}" Foreground="{StaticResource PhoneAccentBrush}" />
<TextBlock Grid.Row="4" Text="Address" FontSize="{StaticResource PhoneFontSizeMediumLarge}" />
<TextBlock Grid.Row="5" Text="{Binding AddressLineOne}" Foreground="{StaticResource PhoneAccentBrush}" />
<Button Grid.Row="6" Content="Edit" CommandParameter="{Binding}" Command="{Binding Path=DataContext.EditUserDetail, ElementName=ApplicationPage}" />
</Grid>
</Border>
<Border Visibility="{Binding EditMode, Converter={StaticResource RowVisibilityConverter}}" Width="450" Margin="0 0 0 20" Padding="15" BorderThickness="2" BorderBrush="{StaticResource PhoneAccentBrush}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="First name"></TextBlock>
<TextBox Grid.Row="1" Text="{Binding FirstName, Mode=TwoWay}" />
<TextBlock Grid.Row="2" Text="Last name"></TextBlock>
<TextBox Grid.Row="3" Text="{Binding LastName, Mode=TwoWay}" />
<TextBlock Grid.Row="4" Text="Address"></TextBlock>
<TextBox Grid.Row="5" Text="{Binding AddressLineOne, Mode=TwoWay}" />
<Button Grid.Row="6" Content="Save" CommandParameter="{Binding}" Command="{Binding Path=DataContext.SaveUserDetail, ElementName=ApplicationPage}" />
</Grid>
</Border>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>