Код позади работает, но MVVM не - PullRequest
1 голос
/ 06 июня 2011

Я возился с чем-то, что работает в коде позади, но когда я пытаюсь привязаться к MVVM, ничего не отображается.Сначала я покажу код, а затем MVVM (тот же xaml).Я хочу использовать MVVM, а не код позади.

Код сзади (работает):

var loadOp = ctx.Load<GateBlox.Web.Models.Structure>(ctx.GetStructuresQuery());
        loadOp.Completed += (s, e) => { _treeView.ItemsSource = loadOp.Entities.Where(struc => !struc.StructureParentFK.HasValue); };

XAML

<Grid x:Name="LayoutRoot">
    <sdk:TreeView x:Name='_treeView' DataContext='{StaticResource ViewModel}'>
        <sdk:TreeView.ItemTemplate>
            <sdk:HierarchicalDataTemplate ItemsSource='{Binding Children}'>
                <TextBlock Text='{Binding StructureName}' />
            </sdk:HierarchicalDataTemplate>
        </sdk:TreeView.ItemTemplate>
    </sdk:TreeView>
</Grid>

MVVM (без привязки)

private LoadOperation<Structure> _loadStructures;
private StructureContext _structureContext;

private IEnumerable<Structure> _structures;
public IEnumerable<Structure> Structures
{
   get { return this._structures; }
   set { this._structures = value; RaisePropertyChanged("Structures"); }
}

public StructuresViewModel()
{
 if (!DesignerProperties.IsInDesignTool)
  {
      _structureContext = new StructureContext();

      _loadStructures = _structureContext.Load(_structureContext.GetStructuresQuery().Where (p=> !  p.StructureParentFK.HasValue));
  _loadStructures.Completed += new EventHandler(_loadStructures_Completed);
   }
}

void _loadStructures_Completed(object sender, EventArgs e)
{
 this.Structures = _loadStructures.Entities;
}

Ответы [ 3 ]

1 голос
/ 06 июня 2011

Проверено ли, что вы не получаете ошибку выражения привязки в выводе?Вы привязываете источник элементов шаблона данных к свойству с именем Children , но ваша модель представления предоставляет источник данных с именем Structures .

Кроме того, в вашей работеНапример, вы устанавливаете ItemSource для TreeView, но в вашем MVVM XAML вы устанавливаете ItemsSource для вашего шаблона данных.Есть ли несоответствие между тем, какой ItemSource вам нужно установить / связать?

Можно также рассмотреть возможность использования источника данных коллекции, который реализует интерфейс INotifyCollectionChanged ( ObservableCollection представить источник привязки как ICollectionView , который использует PagedCollectionView ).

Я рекомендую вам взглянуть на эту информацию о привязке данных в MVVM , поскольку он предоставляет отличные рекомендации по настройке источников данных в моделях представления.

0 голосов
/ 07 июня 2011

Вы не устанавливаете ItemsSource для своего TreeView. Я думаю, что ваш xaml должен выглядеть примерно так:

<Grid x:Name="LayoutRoot">
  <sdk:TreeView x:Name='_treeView' DataContext='{StaticResource ViewModel}'
                ItemsSource="{Binding Structures}">
    <sdk:TreeView.ItemTemplate>
      <sdk:HierarchicalDataTemplate ItemsSource='{Binding Children}'>
         <TextBlock Text='{Binding StructureName}' />
      </sdk:HierarchicalDataTemplate>
    </sdk:TreeView.ItemTemplate>
  </sdk:TreeView>
</Grid>

Надеюсь, это поможет:)

0 голосов
/ 07 июня 2011

У меня уже почти все работает.Я выбрал другой подход и использовал HeirarchicalDataTemplate.На данный момент данные отображаются, но не правильно: запись child1 также становится родительской.Родитель1 (уровень1) Родитель2 (уровень1) Ребенок1 (уровень2) Ребенок1 (уровень1)

<navigation:Page x:Class="GateBlox.Views.Structure"
             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"
             xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
             d:DesignWidth="640"
             d:DesignHeight="480"
             Title="Structure Page"
             xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             xmlns:viewmodel="clr-namespace:GateBlox.ViewModels">

<UserControl.Resources>
    <viewmodel:StructuresViewModel x:Key='ViewModel'>
    </viewmodel:StructuresViewModel>
</UserControl.Resources>

<Grid x:Name="LayoutRoot"
      DataContext='{StaticResource ViewModel}'>
    <Grid.Resources>
        <sdk:HierarchicalDataTemplate x:Key="ChildTemplate"
                                      ItemsSource="{Binding Path=Parent}">
            <TextBlock FontStyle="Italic"
                       Text="{Binding Path=StructureName}" />
        </sdk:HierarchicalDataTemplate>
        <sdk:HierarchicalDataTemplate x:Key="NameTemplate"
                                      ItemsSource="{Binding Path=Children}"
                                      ItemTemplate="{StaticResource ChildTemplate}">
            <TextBlock Text="{Binding Path=StructureName}"
                       FontWeight="Bold" />
        </sdk:HierarchicalDataTemplate>
    </Grid.Resources>
    <sdk:TreeView x:Name='treeView'
                  Width='400'
                  Height='300'
                  ItemsSource='{Binding Structures}'
                  ItemTemplate='{StaticResource NameTemplate}'>
    </sdk:TreeView>
</Grid>

using System;
using System.Collections.ObjectModel;
using GateBlox.Web.Models;
using System.ServiceModel.DomainServices.Client;
using GateBlox.Web.Services;
using GateBlox.Helpers;
using System.ComponentModel;
using System.Collections.Generic;


namespace GateBlox.ViewModels
{
public class StructuresViewModel : ViewModelBase
{
    private LoadOperation<Structure> _loadStructures;
    private StructureContext _structureContext;


    private ObservableCollection<Structure> _structures;
    public ObservableCollection<Structure> Structures
    {
        get { return this._structures; }
        set { this._structures = value; RaisePropertyChanged("Structures"); }
    }

    public StructuresViewModel()
    {
        if (!DesignerProperties.IsInDesignTool)
        {
            _structureContext = new StructureContext();

            _loadStructures = _structureContext.Load(_structureContext.GetStructuresQuery());
            _loadStructures.Completed += new EventHandler(_loadStructures_Completed);
        }
    }

    void _loadStructures_Completed(object sender, EventArgs e)
    {
        this.Structures = IEnumerableConverter.ToObservableCollection(_loadStructures.Entities);
    }
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...