簡體   English   中英

用於綁定的xaml術語的差異

[英]Difference in xaml terms used for binding

我是使用Silverlight的xaml(用於MVVM APPROACH)的初學者。 我讀了幾篇文章,對此一點感到困惑。 如果有人能解釋以下之間的區別,我將非常感激。

假設我的XAML是:

  xmlns:viewmodel="clr-namespace:smallMVVM"
  ......
  ......  
 <UserControl.Resources>
        <viewmodel:ViewModel x:Key="ViewModel"/>
        <viewmodel:DatetimeToDateConverter x:Key="MyConverter"/>
 </UserControl.Resources>

現在有什么區別:

  1. 我的意思是在MainPage.cs中,如果我做"this.DataContext = new ViewModel();" 並在MainPage.xaml中,如果我執行以下<Grid DataContext="{Binding Source={StaticResource ViewModel}}"> 這兩者有什么區別嗎?

  2. 在某些例子中我看到了ItemsSource="{StaticResource customers}" ItemSourceDataContext ItemSource不同。 雖然我在示例(1)中可以看到我在DataContext的Binding中有相同的內容(請參閱: Source={StaticResource ViewModel}而在(2)它被customers替換)。 兩者有何不同?

  3. 有時我也直接看到ItemsSource="{Binding Students}"里面沒有StaticResource 它與StaticResource有何不同?

  4. 一些例子只有Binding="{Binding Name}"

  5. SelectedItemSelectedValue有何不同?

有人可以用一個簡單的小例子解釋一下嗎? 在互聯網搜索中,有一些典型的例子供初學者理解。

1)從技術上講,數據上下文的兩個聲明之間沒有區別我喜歡在代碼隱藏中執行它,如下所示:

Partial Public Class MainPage
    Inherits UserControl

    Private _viewModel As TestViewModel

    Public Sub New()
        InitializeComponent()
        _viewModel = TryCast(Resources("TheViewModel"), TestViewModel)
        Me.DataContext = _viewModel
    End Sub
End Class

2)您不希望將ItemsSource設置為靜態頁面資源,您希望將其設置為ViewModel中的Property。 下面是一個示例View和ViewModel,注意VM上的繼承和Impelments,這些允許您的VM告訴您的View已更改屬性,並重新加載該屬性。

視圖:

<UserControl x:Class="SilverlightTestApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:ModelViewModel="clr-namespace:SilverlightTestApp"  >

<UserControl.Resources>
    <ModelViewModel:TestViewModel x:Key="TheViewModel" />
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource TheViewModel}">
    <ItemsControl ItemsSource="{Binding SampleCollection}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"></TextBlock>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

視圖模型:

Imports System.ComponentModel
Imports System.Collections.ObjectModel
Public Class TestViewModel
    Inherits DependencyObject
    Implements System.ComponentModel.INotifyPropertyChanged
    Implements INotifyDataErrorInfo

    Private _model As TestModel

    Sub New()
        Me.New(New TestModel)
    End Sub

    Public Sub New(ByVal model As TestModel)
        _model = model

        _sampleCollection = New ObservableCollection(Of String)
        _sampleCollection.Add("one")
        _sampleCollection.Add("two")
        _sampleCollection.Add("three")
        _sampleCollection.Add("four")

    End Sub

    Private _sampleCollection As ObservableCollection(Of String)
    Public Property SampleCollection As ObservableCollection(Of String)
        Get
            Return _sampleCollection
        End Get
        Set(value As ObservableCollection(Of String))             
            If value IsNot Nothing Then
                _sampleCollection = value
            End If
            Me.OnPropertyChanged("SampleCollection")

        End Set
    End Property

    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

    Protected errors As New Dictionary(Of String, List(Of String))

    Protected Sub OnPropertyChanged(ByVal propertyName As String)
        RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs(propertyName))
    End Sub

    ' #Region " Validation Plumbing"
    ' Adds the specified error to the errors collection if it is not 
    ' already present, inserting it in the first position if isWarning is 
    ' false. Raises the ErrorsChanged event if the collection changes. 
    Public Sub AddError(ByVal propertyName As String, ByVal [error] As String,
                        ByVal isWarning As Boolean)

        If Not errors.ContainsKey(propertyName) Then _
            errors(propertyName) = New List(Of String)()

        If Not errors(propertyName).Contains([error]) Then
            If isWarning Then
                errors(propertyName).Add([error])
            Else
                errors(propertyName).Insert(0, [error])
            End If
            RaiseErrorsChanged(propertyName)
        End If

    End Sub

    ' Removes the specified error from the errors collection if it is
    ' present. Raises the ErrorsChanged event if the collection changes.
    Public Sub RemoveError(ByVal propertyName As String, ByVal [error] As String)

        If errors.ContainsKey(propertyName) AndAlso
            errors(propertyName).Contains([error]) Then

            errors(propertyName).Remove([error])
            If errors(propertyName).Count = 0 Then errors.Remove(propertyName)
            RaiseErrorsChanged(propertyName)

        End If

    End Sub
    Public Sub RemoveError(ByVal propertyName As String)

        If errors.ContainsKey(propertyName) Then

            errors.Remove(propertyName)
            RaiseErrorsChanged(propertyName)

        End If

    End Sub

    Public Sub RaiseErrorsChanged(ByVal propertyName As String)
        OnPropertyChanged("HasErrors")
        RaiseEvent ErrorsChanged(Me,
            New DataErrorsChangedEventArgs(propertyName))
    End Sub

    Public Event ErrorsChanged As EventHandler(Of DataErrorsChangedEventArgs) _
        Implements INotifyDataErrorInfo.ErrorsChanged

    Public Function GetErrors(ByVal propertyName As String) _
        As System.Collections.IEnumerable _
        Implements INotifyDataErrorInfo.GetErrors

        If (String.IsNullOrEmpty(propertyName) OrElse
            Not errors.ContainsKey(propertyName)) Then Return Nothing
        Return errors(propertyName)

    End Function

    Public ReadOnly Property HasErrors As Boolean _
        Implements INotifyDataErrorInfo.HasErrors
        Get
            Return errors.Count > 0
        End Get
    End Property

End Class

上面的關鍵部分是Me.OnPropertyChanged("SampleCollection") ,它告訴View更新它綁定的屬性。

關於體系結構的注釋,如果要構建具有多個View和ViewModel的應用程序,則創建ViewModelBase並使其繼承DependencyObject並實現INotifyPropertyChanged,然后所有實際視圖模型都可以從ViewModelBase繼承。

我還創建了一個名為TestModel的類,它在VM中使用,但保留為空。 該模型是您將代碼與數據庫進行通信的地方,或者我所做的,調用與我的數據庫通信的WCF服務。

5)最后,SelectedItem是ItemSource中選擇的實際對象,而SelectedValue是SelectedValuePath的值。 在上面的示例中,我創建了一個簡單的String集合,但是假設您有一組具有多個屬性的自定義對象,您可以將SelectedValuePath指定為其中一個屬性。 SelectedItem將返回整個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM