无法将ItemsControl.ItemTemplate绑定到List <object>元素</object>

时间:2015-03-23 08:58:35

标签: wpf list xaml binding itemscontrol

我遇到了麻烦。我创建了UserControl,如下所示:

enter image description here

http://i.stack.imgur.com/ITxkS.jpg

我将依赖属性“Text”绑定到UserControl的TextBlock.Text。我想创建另一个可视化List的UserControl。这是我的代码:

<UserControl x:Class="ListPresenter.ListViewer"
         xmlns:dop="clr-namespace:DeletableObjectPresenter;assembly=DeletableObjectPresenter"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
      <ItemsControl ItemsSource="{Binding List, RelativeSource={RelativeSource AncestorType=UserControl}}">
          <ItemsControl.ItemsPanel>
             <ItemsPanelTemplate>
                 <WrapPanel></WrapPanel>
             </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
          <ItemsControl.ItemTemplate>
              <ItemContainerTemplate>
                  <dop:DeletableObjectPresenter></dop:DeletableObjectPresenter>
              </ItemContainerTemplate>
          </ItemsControl.ItemTemplate>
      </ItemsControl>
</Grid>

...

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

namespace ListPresenter
{
    /// <summary>
    /// Interaction logic for ListViewer.xaml
    /// </summary>
    public partial class ListViewer : UserControl
    {
        public static readonly DependencyProperty ListProperty =                     DependencyProperty.Register(
        "List", typeof (IList<object>), typeof (ListViewer), new PropertyMetadata(null));
        public List<object> List 
        {
            get { return (List<object>) GetValue(ListProperty); }
            set { SetValue(ListProperty, value); }
        }
        public ListViewer()
        {
            InitializeComponent();
        }
    }
}

以下是我的控制:

enter image description here

http://i.stack.imgur.com/JIjHy.jpg

问题是我不知道如何将Item的Text绑定到list的元素。谢谢!

1 个答案:

答案 0 :(得分:0)

要做的第一件事就是为Text中的UserControl媒体资源创建DependencyProperty。您应该在UserControl

中将数据绑定到此属性
<TextBlock Text="{Binding Text, RelativeSource={RelativeSource 
    AncestorType={x:Type dop:DeletableObjectPresenter}}}" />

现在,您可以通过Text将数据绑定到UserControl的{​​{1}}属性:

ItemsControl.ItemTemplate

当然,<ItemsControl.ItemTemplate> <DataTemplate> <dop:DeletableObjectPresenter Text="{Binding PropertyToBindToText}" /> </DataTemplate> </ItemsControl.ItemTemplate> 集合中的对象需要拥有一个属性(在此示例中名为List),以便将数据绑定到PropertyToBindToText的{​​{1}}属性}。因此,您最好不要创建强类型集合而不是Text,而且习惯上在WPF中使用UserControl

有关详细信息,请参阅MSDN上的Data Binding Overview页面。

相关问题