更改 MainWindow.xaml 后 ListBox 出现 DataContext 问题



本月是WPF和MVVM设计模式的新手,而且总体上有点不合实际。 为了学习,我一直在尝试文本框、矩形以及在窗口中显示它们的方法。 我从 Ashley Davis 出色的"WPF 中的简单拖动选择"教程开始,该教程介绍了为矩形集合创建视图模型、将列表框绑定到该集合、使用画布设置列表框样式、为矩形创建数据模板以及基本的"橡皮筋"选择逻辑。

此后,我以本教程为基础来改进拖动选择,使其行为更像 Windows 资源管理器中的选择,并允许从角或边缘调整矩形的大小。

一切都很好,直到我更改了 MainWindow.xaml,努力在侧面包含用于各种按钮和控件的列,从而将"编辑器表面"网格从主窗口上的 1x1 网格内移动到 1x2 网格的列,将数据模板移动到网格的资源(因为它将是窗口中唯一需要它的元素)。一旦我这样做了,我编写的与列表框交互的子例程就开始行为不端 - 橡皮筋选择不再有效。 没有视觉指示列表框项正在被选中(它们之前已突出显示),并且在拖动选择鼠标Up事件后查询listBox.SelectedItems.Count将返回零。

经过一些实验,阅读了此站点上的许多问题和我的 WPF Unleashed 书籍的各个部分,并浏览了 msdn 数据绑定概述,截至今天早上,我仍然找不到我的错误。 我认为这是一个数据绑定错误或不正确的数据上下文。

有关所涉及的视图模型的一些详细信息:

数据字段视图模型

。实现 INotifyPropertyChanged 并公开其(在本例中为矩形和文本框)X,Y 位置、宽度、高度、可见性和选择状态的属性(一种在多个橡皮筋选择操作中跟踪它的方法)

页面视图模型

。实现 INotifyPropertyChanged,并具有 DataFieldViewModel 类型的 ObservableCollection,称为 DataFields,并将其公开为 ReadOnly 属性。

以下是MainWindow.xaml.vb以及其中一个损坏的子文件:

Namespace EditorUI

'
' The main window of the editor.
'
Partial Public Class MainWindow
    Inherits Window
    '
    ' Temporary.  Will be replaced with a collection of pages eventually
    '
    Private Pages As PageViewModel

(为简洁起见,截取了其余数据成员和属性)

    Public Sub New()
        InitializeComponent()
        Pages = New PageViewModel
    End Sub

(这是有问题的潜艇之一)

 '
    ' Select all the data fields that intersect the selection rectangle.
    ' Remove any selected data fields which do not.
    '
    Private Sub ApplyDragSelectionRectangle()
        If (LeftMouseDrag) Then
            Dim selectionRectangle As New Rect(Canvas.GetLeft(selectionRectangleBorder), _
                                               Canvas.GetTop(selectionRectangleBorder), _
                                               selectionRectangleBorder.Width, _
                                               selectionRectangleBorder.Height)
            '
            ' Find and select all the list box items.
            '
            For Each dataFieldViewModel As DataFieldViewModel In Me.Pages.GetDataFields
                Dim hitBox As New Rect(dataFieldViewModel.hbX, _
                                       dataFieldViewModel.hbY, _
                                       dataFieldViewModel.hbWidth, _
                                       dataFieldViewModel.hbHeight)
                If (selectionRectangle.IntersectsWith(hitBox)) Then
                    If (dataFieldViewModel.ExistingSelection) Then
                        '
                        ' data field is already part of an existing selection; unselect it
                        '
                        Me.DataFieldListBox.SelectedItems.Remove(dataFieldViewModel)
                    Else
                        Me.DataFieldListBox.SelectedItems.Add(dataFieldViewModel)
                    End If
                End If
                If Not (selectionRectangle.IntersectsWith(hitBox)) Then
                    If (dataFieldViewModel.ExistingSelection) Then
                        '
                        ' data field was part of an existing selection; reselect it
                        '
                        Me.DataFieldListBox.SelectedItems.Add(dataFieldViewModel)
                    Else
                        Me.DataFieldListBox.SelectedItems.Remove(dataFieldViewModel)
                    End If
                End If
            Next
        Else
            dragSelectionCanvas.Visibility = Visibility.Collapsed
            '
            ' update all data fields' existing selection status to the new
            ' selection (first set them all to false to catch data fields 
            ' that were removed)
            '
            For Each dataFieldViewModel As DataFieldViewModel In Me.DataFieldListBox.Items
                dataFieldViewModel.ExistingSelection = False
            Next
            For Each dataFieldViewModel As DataFieldViewModel In Me.DataFieldListBox.SelectedItems
                dataFieldViewModel.ExistingSelection = True
            Next
        End If
    End Sub

最后,下面是完整的 XAML:

<Window x:Class="EditorUI.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Editor_UI_Experiments.EditorUI"
    Title="Editor UI Experiments" 
    Width="900"
    Height="600"
    Loaded="Window_Loaded" 
    >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="778*" />
        </Grid.ColumnDefinitions>
        <Button
            Grid.Column="0"
            VerticalAlignment="Top"
            Height="25"
            Content="Explode :D"
            Name="Button1" 
            />
        <Grid
            Name="EditorSurface"
            Grid.Column="1"
            MouseDown="Editor_MouseDown"
            MouseUp="Editor_MouseUp"
            MouseMove="Editor_MouseMove"
            >
            <Grid.Background>
                <ImageBrush ImageSource="{Binding GetPageImage}" />
            </Grid.Background>
            <Grid.DataContext>
                <local:PageViewModel/>
            </Grid.DataContext>
            <Grid.Resources>
                <!--
                A data template that defines the visuals for a data field.
                -->
                <DataTemplate 
                DataType="{x:Type local:DataFieldViewModel}"
                    >
                    <!-- 
                    The data field is embedded in a Grid so that we can set the Margin
                    The margin is set so that the ListBox item selection fits nicely around the Rectangle.
                    -->
                    <Grid
                    Margin="0,2,2,2"
                        >
                        <!-- 
                        text box where the data field's response lives (it could be a Database tag,
                        or a check mark, or custom response)
                        -->
                        <TextBox
                        Width="{Binding Width}"
                        Height="{Binding Height}"
                        Background="LightBlue"
                        Cursor="IBeam"
                        MouseDown="TextBox_MouseDown"
                        MouseUp="TextBox_MouseUp"
                        MouseMove="TextBox_MouseMove"
                        Text="Example Text"
                            />
                        <!-- 
                        rectangle that lives on top of the text field to aid in positioning the data field
                        -->
                        <Rectangle
                        Width="{Binding Width}"
                        Height="{Binding Height}"
                        Stroke="LightBlue"
                        StrokeThickness="5"
                        Fill="White"
                        Opacity="0.5"
                        Cursor="SizeAll"
                        MouseDown="Rectangle_MouseDown"
                        MouseUp="Rectangle_MouseUp"
                        MouseMove="Rectangle_MouseMove"
                        Visibility="{Binding Visibility}"
                            />
                        <!--
                        Thumb "handles" to give the user a way to resize the data field
                        -->
                        <!-- 
                        These four live in the corners of a data field and allow resizing on
                        X and Y simultaneously
                        -->
                        <Rectangle
                        Width="7"
                        Height="7"
                        VerticalAlignment="Top"
                        HorizontalAlignment="Left"
                        Margin="-1,-1,0,0"
                        Cursor="SizeNWSE"
                        Fill="LightGray"
                        Stroke="Gray"
                        Opacity="0.6"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <Rectangle
                        Width="7"
                        Height="7"
                        VerticalAlignment="Top"
                        HorizontalAlignment="Right"
                        Margin="0,-1,-1,0"
                        Cursor="SizeNESW"
                        Fill="LightGray"
                        Stroke="Gray"
                        Opacity="0.6"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <Rectangle
                        Width="7"
                        Height="7"
                        VerticalAlignment="Bottom"
                        HorizontalAlignment="Left"
                        Margin="-1,0,0,-1"
                        Cursor="SizeNESW"
                        Fill="LightGray"
                        Stroke="Gray"
                        Opacity="0.6"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <Rectangle
                        Width="7"
                        Height="7"
                        VerticalAlignment="Bottom"
                        HorizontalAlignment="Right"
                        Margin="0,0,-1,-1"
                        Cursor="SizeNWSE"
                        Fill="LightGray"
                        Stroke="Gray"
                        Opacity="0.6"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <!--
                        These four live along the data field's edges and allow resizing in the X
                        or Y direction only.  They have zero opacity to avoid visual clutter
                        -->
                        <Rectangle
                        Height="5"
                        VerticalAlignment="Top"
                        HorizontalAlignment="Stretch"
                        Margin="7,0,7,0"
                        Cursor="SizeNS"
                        Fill="Yellow"
                        Opacity="0"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <Rectangle
                        Height="5"
                        VerticalAlignment="Bottom"
                        HorizontalAlignment="Stretch"
                        Margin="7,0,7,0"
                        Cursor="SizeNS"
                        Fill="Yellow"
                        Opacity="0"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <Rectangle
                        Width="5"
                        VerticalAlignment="Stretch"
                        HorizontalAlignment="Left"
                        Margin="0,7,0,7"
                        Cursor="SizeWE"
                        Fill="Yellow"
                        Opacity="0"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />
                        <Rectangle
                        Width="5"
                        VerticalAlignment="Stretch"
                        HorizontalAlignment="Right"
                        Margin="0,7,0,7"
                        Cursor="SizeWE"
                        Fill="Yellow"
                        Opacity="0"
                        Visibility="{Binding Visibility}"
                        MouseDown="Thumb_MouseDown"
                        MouseUp="Thumb_MouseUp"
                        MouseMove="Thumb_MouseMove"
                            />                            
                    </Grid>
                </DataTemplate>
            </Grid.Resources>
            <!--
            This ListBox presents the data fields
            The data template that defines the visuals for each data field is in the 
            resources section at the start of this file.
            -->
            <ListBox
                x:Name="DataFieldListBox"
                ItemsSource="{Binding GetDataFields}"
                SelectionMode="Extended"
                Background="Transparent"
                >
                <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Canvas />
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.ItemContainerStyle>
                        <Style
                            TargetType="ListBoxItem"
                            >
                            <Setter
                            Property="Canvas.Left"
                            Value="{Binding X}"
                            />
                            <Setter
                            Property="Canvas.Top"
                            Value="{Binding Y}"
                            />
                        </Style>
                    </ListBox.ItemContainerStyle>
            </ListBox>
            <!--
            Render a drag selection rectangle using a Canvas with a border
            -->
            <Canvas
            x:Name="dragSelectionCanvas"
            Visibility="Collapsed"
                >
                <Border 
                x:Name="selectionRectangleBorder"
                BorderBrush="Blue"
                BorderThickness="1"
                Background="LightBlue"
                CornerRadius="1"
                Opacity="0.5"
                />
            </Canvas>
    </Grid>
</Grid>

我确信我的代码充满了新手错误,但到目前为止它很有趣。希望快速改进,也许可以将其变成有用的东西。 非常欢迎反馈和见解。 如果有人碰巧发现我哪里出错了,你会得到我的感激。

-汤姆

我怀疑这与您在 XAML 中定义 Grid 的DataContext有关,但您的拖动事件引用了代码隐藏中的对象。因此,ListBox绑定到 PageViewModel 的 XAML 副本,而代码隐藏正在使用不同的PageViewModel副本

我建议从 XAML 中删除 DataContext 属性,改为在代码隐藏中设置它,例如Me.DataContext = Pages

请记住,除非是应用程序启动代码,否则在代码隐藏中设置DataContext通常是不好的做法。