[英]Trouble with Binding Item in WP8
我開發了一個筆記應用程序,使用ItemsNote保存注釋列表,並使用ItemModifyNote修改時保存臨時項目。
public ObservableCollection<NoteViewModel> ItemsNote
{
get
{
return _itemsNote;
}
set
{
_itemsNote = value;
NotifyPropertyChanged("ItemsNote");
}
}
public NoteViewModel ItemModifyNote { get; set; }
在Mainpage.xaml(我在LongListSelector中顯示ItemsNote綁定的位置)上,在每個注釋旁邊插入一個“編輯”按鈕,因此當我單擊它時,我將ItemModifyNote的數據設置為ItemsNote中的選定項目,然后導航到“ modifyNotePage.xaml”
private void btEditNote_Click(object sender, RoutedEventArgs e)
{
var button = (sender as Button).DataContext as NoteViewModel;
if (button != null)
{
int intIndex = App.ViewModel.ItemsNote.IndexOf(button);
string modifyUri = "/Pages/NoteModifyPage.xaml?Id=" + intIndex.ToString();
App.ViewModel.ItemModifyNote = App.ViewModel.ItemsNote.ElementAt(intIndex);
NavigationService.Navigate(new Uri(modifyUri, UriKind.RelativeOrAbsolute));
}
}
在ModifyNotePage.xaml,我通過2個文本框修改ItemModifyNote的數據(包括標題和內容,兩者都是字符串)
<TextBox Grid.Column="1"
Text="{Binding ItemModifyNote.NoteTitle, Mode=TwoWay}" x:Name="tbxModifyNoteTitle"
FontFamily="Clear Sans Light" BorderThickness="0.0"
KeyDown="tbxModifyNoteTitle_KeyDown"/>
</Grid>
<TextBox Grid.Row="1" Margin="0,0,0,20"
x:Name="tbxModifyNoteContent" Text="{Binding ItemModifyNote.NoteContent, Mode=TwoWay}"
AcceptsReturn="True" TextWrapping="Wrap" BorderThickness="0.0" FontFamily="Clear Sans Light"
GotFocus="tbxModifyNoteContent_GotFocus" LostFocus="tbxModifyNoteContent_LostFocus"/>
最后,我使用2個按鈕:“取消”和“保存”。
在“保存”按鈕中,我通過ItemModifyNote的數據設置ItemsNote中的項目數據
private void btCancel_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
}
private void btSave_Click(object sender, EventArgs e)
{
App.ViewModel.ItemsNote[key] = App.ViewModel.ItemModifyNote;
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
}
問題是:即使單擊取消按鈕,注釋仍會保存修改文本?
這是因為ItemModifyNote
引用NoteViewModel
從實例ItemsNote
。 由於編輯頁面中的TextBox
和LongListSelector
中的LongListSelector
在同一veiwmodel實例上運行,因此當用戶修改ItemModifyNote
屬性時, LongListSelector
將顯示更新的值,而無需任何其他代碼。
為了避免這種情況,在按鈕編輯點擊事件處理方法,嘗試創建一個新的實例NoteViewModel
並復制它從一個在屬性值ItemsNote
,而不是直接引用現有的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.