绑定到DataConmplate for ItemsControl中的自定义控件

当我想绑定到我的自定义用户控件时,我遇到了基于ItemsControl定义的DataType DataTemplate绑定问题。

出于演示目的,我创建了简单的Item类示例,其中我有这样的项集合:

 public class Item { public string ItemNameToBeSureWhatPropertyIsBound { get; set; } } 

在我的ViewModel中,我创建了这样的集合,并将其公开(有一个项目可以单独进行比较):

 public class MainWindowViewModel : INotifyPropertyChanged { private ObservableCollection _items; private Item _exampleItem; public MainWindowViewModel() { Items = new ObservableCollection(new[] { new Item { ItemNameToBeSureWhatPropertyIsBound = "Me" }, new Item { ItemNameToBeSureWhatPropertyIsBound = "MySelf" }, new Item { ItemNameToBeSureWhatPropertyIsBound = "Ich" }, }); ExampleItem = Items.LastOrDefault(); } public ObservableCollection Items { get { return _items; } set { _items = value; OnPropertyChanged(); } } public Item ExampleItem { get { return _exampleItem; } set { _exampleItem = value; OnPropertyChanged();} } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } 

我的自定义用户控件定义如下:

      

…它后面的代码中有一个DependencyProperty

 public partial class ItemRowUserControl : UserControl { public ItemRowUserControl() { InitializeComponent(); } public static readonly DependencyProperty ItemNameProperty = DependencyProperty.Register( "ItemName", typeof (string), typeof (ItemRowUserControl), new PropertyMetadata(default(string))); public string ItemName { get { return (string) GetValue(ItemNameProperty); } set { SetValue(ItemNameProperty, value); } } } 

问题是,当我尝试在DataTemplate中为ItemsControl绑定Item的属性时,我正在MainWindow中这样做(注意:我有虚拟转换器仅用于调试目的,返回值,仅此而已):

                     <!--  -->        

现在,如果我绑定到我的自定义ItemRowUserControl,我进入转换器的值(我在调试输出中看到相同的)是ItemRowUserControl本身。 但是,如果我绑定到注释掉的代码,一切正常。 为什么这样,我怎样才能对DataTemplate进行自定义控制,以便绑定(由intellisense提供)可以工作? 旁注:在网格行1(底部)中绑定到我的ItemRowUserControl工作正常,所以我猜控制设置为按预期工作?

问题是您明确将UserControl的DataContext设置为自身:

 DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}} 

删除该赋值并编写ItemName绑定,如下所示:

  

或者像这样