【问题标题】:Trouble with Binding Item in WP8WP8中绑定项目的问题
【发布时间】:2014-06-05 04:32:41
【问题描述】:

我开发了一个笔记应用,使用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 中的选定项目,然后导航到“修改NotePage.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));
}

问题是:即使我点击了取消按钮,注释仍然保存修改文本???

【问题讨论】:

    标签: c# xaml windows-phone-8 binding


    【解决方案1】:

    那是因为ItemModifyNote 引用了来自ItemsNoteNoteViewModel 实例。由于编辑页面中的TextBox 和主页中的LongListSelector 都在同一个veiwmodel 实例上运行,因此当用户修改ItemModifyNote 属性时,LongListSelector 将显示更新后的值,而无需任何更多代码。

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

    【讨论】:

    • 嗯,我已经改变了 App.ViewModel.ItemModifyNote = App.ViewModel.ItemsNote.ElementAt(intIndex);与 App.ViewModel.ItemModifyNote = new NoteViewModel(){NoteTitle = ..., NoteContent = ...}; ,这似乎奏效了。谢谢^^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多