Привязка данных к ViewBase - PullRequest
       11

Привязка данных к ViewBase

0 голосов
/ 12 ноября 2010

Я пытаюсь использовать ViewBase для привязки некоторых данных к ListView одним нажатием кнопки.Кажется, это не работает, и я не знаю, что я делаю неправильно.Вот короткая автономная программа, которая отражает эту проблему:

Главное окно:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2;assembly="
    Title="MainWindow" Height="350" Width="525">
  <Window.Resources>
    <DataTemplate x:Key="ListViewItemTemplate" DataType="ListViewItem">
      <Border Name="LastBorder">
        <Grid>
          <Grid.RowDefinitions>
            <RowDefinition Height="*" />
          </Grid.RowDefinitions>
          <Rectangle Height="{Binding Height}" Width="{Binding Width}" Fill="{Binding Fill}"/>
        </Grid>
      </Border>
    </DataTemplate>
    <Style TargetType="ListViewItem" x:Key="ItemContainerStyle1">
      <Setter Property="VerticalAlignment" Value="Top" />
    </Style>
    <ObjectDataProvider x:Key="ShapeProvider" />


  </Window.Resources>
  <Grid>
    <Button Content="Bind data" Click="Button_Click" Height="20" Width="80" Margin="12,12,410,278" />
    <ListView ItemsSource="{Binding Path=.,Source={StaticResource ShapeProvider}}"
         ItemContainerStyle="{StaticResource ItemContainerStyle1}" x:Name="ListView1" Height="113" VerticalAlignment="Bottom">
      <ListView.View>
        <local:PlainView ItemWidth="148" ItemHeight="250"
                 ItemTemplate="{StaticResource ListViewItemTemplate}" />
      </ListView.View>
    </ListView>
  </Grid>
</Window>

Моя база просмотра:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WpfApplication2
{
  public class PlainView : ViewBase
  {
    public static readonly DependencyProperty ItemContainerStyleProperty =
      ItemsControl.ItemContainerStyleProperty.AddOwner(typeof(PlainView));

    public Style ItemContainerStyle
    {
      get { return (Style)GetValue(ItemContainerStyleProperty); }
      set { SetValue(ItemContainerStyleProperty, value); }
    }

    public static readonly DependencyProperty ItemTemplateProperty =
      ItemsControl.ItemTemplateProperty.AddOwner(typeof(PlainView));

    public DataTemplate ItemTemplate
    {
      get { return (DataTemplate)GetValue(ItemTemplateProperty); }
      set { SetValue(ItemTemplateProperty, value); }
    }

    public static readonly DependencyProperty ItemWidthProperty =
      WrapPanel.ItemWidthProperty.AddOwner(typeof(PlainView));

    public double ItemWidth
    {
      get { return (double)GetValue(ItemWidthProperty); }
      set { SetValue(ItemWidthProperty, value); }
    }

    public static readonly DependencyProperty ItemHeightProperty =
      WrapPanel.ItemHeightProperty.AddOwner(typeof(PlainView));

    public double ItemHeight
    {
      get { return (double)GetValue(ItemHeightProperty); }
      set { SetValue(ItemHeightProperty, value); }
    }

    protected override object DefaultStyleKey
    {
      get
      {
        ComponentResourceKey key = new ComponentResourceKey(GetType(), "PlainViewRsx");
        return key;
      }
    }

    public PlainView()
    {
      ItemWidth = 40;
      ItemHeight = 20;
    }
  }
}

Стиль просмотра:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:WpfApplication2">
  <!--PlainView Default Style for ListView-->
  <Style x:Key="{ComponentResourceKey 
    TypeInTargetAssembly={x:Type local:PlainView},
    ResourceId=PlainViewRsx}" 
    TargetType="{x:Type ListView}" 
    BasedOn="{StaticResource {x:Type ListBox}}">

    <!--
    Width="{Binding (FrameworkElement.ActualWidth), RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}"
    -->

    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    <Setter Property="ItemContainerStyle" 
      Value="{Binding (ListView.View).ItemContainerStyle, RelativeSource={RelativeSource Self}}" />
    <Setter Property="ItemTemplate" 
      Value="{Binding (ListView.View).ItemTemplate, RelativeSource={RelativeSource Self}}" />
    <Setter Property="ItemsPanel">
      <Setter.Value>
        <ItemsPanelTemplate>
          <WrapPanel HorizontalAlignment="Stretch"
            Width="{Binding (FrameworkElement.ActualWidth), RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}"
            ItemWidth="{Binding (ListView.View).ItemWidth, RelativeSource={RelativeSource AncestorType=ListView}}"
            MinWidth="{Binding (ListView.View).ItemWidth, RelativeSource={RelativeSource AncestorType=ListView}}"
            ItemHeight="{Binding (ListView.View).ItemHeight, RelativeSource={RelativeSource AncestorType=ListView}}" />
        </ItemsPanelTemplate>
      </Setter.Value>
    </Setter>
  </Style>
  </ResourceDictionary>

И объект, который я использую:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Media;

namespace WpfApplication2
{
  public class RectShapes : INotifyPropertyChanged
  {
    public int Height { get; set; }
    public int Width { get; set; }
    public SolidColorBrush Fill { get; set; }

    public RectShapes()
    {
      Width = 98;
      Height = 152;
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(name));
      }
    }
  }
}

Я использовал snoop, чтобы проверить, есть ли ошибка привязки, но кажется, что у списка нет даже дочернего элемента, поэтому PlainViewне добавляется каким-либо образом, хотя у меня есть набор в XAML.

Спасибо!

Ответы [ 2 ]

0 голосов
/ 13 ноября 2010

Хорошо, теперь я вижу: D

Я работаю над проектом, который также требует простого просмотра, вот как я это сделал:

<Window.Resources>
      <DataTemplate x:Key="iconTemplate">
        <DockPanel Height="40" Width="150">
            <Image Margin="6" Height="30" Width="30" 
                   Stretch="Uniform"
                   Source={Binding Pic}>
            </Image>
            <TextBlock DockPanel.Dock="Top" Text="{Binding Title}"
                       FontSize="13" HorizontalAlignment="Left"
                       Margin="0,0,0,3"/>
            <TextBlock Text="{Binding Artist}" FontSize="9"
                       HorizontalAlignment="Left" Margin="0,0,0,3"/>
        </DockPanel>
    <my:PlainView x:Key="iconView" 
        ItemTemplate="{StaticResource iconTemplate}" 
        ItemWidth="300"/>
</Window.Resources>

Мой обычный вид использует примерно тот же код, что и ваш, и эта разметка с легкостью оборачивает мои значки, поэтому я думаю, что она может помочь вам

0 голосов
/ 12 ноября 2010

Не думаю, что с представлением что-то не так.

Я думаю, что проблема может быть найдена здесь:

<ListView ItemsSource="{Binding Path=.,Source={StaticResource ShapeProvider}}"
     ItemContainerStyle="{StaticResource ItemContainerStyle1}" x:Name="ListView1" Height="113" VerticalAlignment="Bottom">

попробуйте вместо этого:

<ListView ItemsSource="{Binding Source={StaticResource ShapeProvider}}"
     ItemContainerStyle="{StaticResource ItemContainerStyle1}" x:Name="ListView1" Height="113" VerticalAlignment="Bottom">

или просто для устранения неполадок, удалите представление и запустите ваш код, если в просмотре списка ничего не отображается, проблема с привязкой.

...