繁体   English   中英

WP8中的绑定项目有问题

[英]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 由于编辑页面中的TextBoxLongListSelector中的LongListSelector在同一veiwmodel实例上运行,因此当用户修改ItemModifyNote属性时, LongListSelector将显示更新的值,而无需任何其他代码。

为了避免这种情况,在按钮编辑点击事件处理方法,尝试创建一个新的实例NoteViewModel并复制它从一个在属性值ItemsNote ,而不是直接引用现有的实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM