WPF设计时间设置窗口的数据上下文没有错误

时间:2014-01-08 13:46:28

标签: wpf xaml datacontext

我的XAML文件是:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ViewModels="clr-namespace:Bookstore.Bookstore.ViewModels"
    x:Class="Bookstore.Views.MainWiew" 
    Title="Main Wiew" Height="350" Width="525">

    <Window.DataContext>
        <ViewModels:MainViewModel />
    </Window.DataContext>

    <Grid> 
    ...
    </Grid>
</Window>

当我跑步时,没关系。没问题。

但在设计时,有1个错误:

  

无法找到数据源文件

我不想在codebehind中添加datacontext。

那么,我该如何清理错误列表

修改

我的MainViewModel.vb文件:

Imports System.Collections.ObjectModel
Imports Bookstore.Bookstore.Models
Imports Bookstore.Bookstore.Commands
Imports System.Windows
Imports System.Windows.Input


Namespace Bookstore.ViewModels
Public Class MainViewModel
    Inherits ViewModelBase

    Sub New()
        LoadBooks()
    End Sub

    Private _currentBook As Book
    Private _books As New ObservableCollection(Of Book)()
    Private _bookstoreRepository As IBookstoreRepository = New BookstoreRepository()
    Private _removeBookCommand As ICommand

#Region "Public Properties"
    Public Property Books() As ObservableCollection(Of Book)
        Get
            Return _books
        End Get
        Set(value As ObservableCollection(Of Book))

        End Set
    End Property

    Public Property CurrentBook As Book
        Get
            Return _currentBook
        End Get
        Set(value As Book)
            _currentBook = value
            OnPropertyChanged("CurrentBook")
        End Set
    End Property

    Public Property RemoveBookCommand() As ICommand
        Get
            If _removeBookCommand Is Nothing Then
                _removeBookCommand = New DelegateCommand(Of Book)(AddressOf RemoveBook, AddressOf CanRemoveBook)
            End If
            Return _removeBookCommand
        End Get
        Set(value As ICommand)

        End Set
    End Property
#End Region

#Region "Functions"
    Private Sub LoadBooks()
        For Each book As Book In _bookstoreRepository.GetBooks()
            _books.Add(book)
        Next
    End Sub

    Private Function CanRemoveBook(book As Book) As Boolean
        Return Books.Count > 0 And Books.Contains(book)
    End Function

    Private Sub RemoveBook(book As Book)
        Books.Remove(book)
        CurrentBook = Nothing
    End Sub
#End Region

End Class

End Namespace

1 个答案:

答案 0 :(得分:1)

您可以使用DesignerProperties.GetIsInDesignMode方法检查设计时间,然后返回空数据或样本数据,而不是从外部源加载的数据。这将在设计器中显示样本数据。