一尘不染

绑定到ItemsControl的DataTemplate内部的自定义控件

c#

我有绑定的问题DataTemplate基础上定义DataTypeItemsControl,当我想结合我的 自定义用户控件

出于演示目的,我创建了一个简单的 Item类 示例,其中收集了以下项目:

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

在我的 ViewModel中, 我创建了这样的集合,并公开了它(其中一个用于单独比较):

public class MainWindowViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Item> _items;
    private Item _exampleItem;

    public MainWindowViewModel()
    {
        Items = new ObservableCollection<Item>(new[] { new Item { ItemNameToBeSureWhatPropertyIsBound = "Me" }, new Item { ItemNameToBeSureWhatPropertyIsBound = "MySelf" }, new Item { ItemNameToBeSureWhatPropertyIsBound = "Ich" }, });
        ExampleItem = Items.LastOrDefault();
    }

    public ObservableCollection<Item> 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));
    }
}

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

<UserControl x:Class="WpfDataTemplate.ItemRowUserControl"
         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="40" d:DesignWidth="300"
         x:Name="ItemRowControl" DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}">

    <Grid Background="Yellow" Height="40">
        <TextBlock Text="{Binding ItemName}" Foreground="Black"/>
    </Grid>
</UserControl>

......它有一个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); }
    }
}

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

<Window.DataContext>
    <my:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
    <my:MyDummyConverter x:Key="MyDummyConverter" />
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="50" />
    </Grid.RowDefinitions>

    <ItemsControl Name="ItemsControl" ItemsSource="{Binding Items}" Grid.Row="0" Background="Red">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>

        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type my:Item}">
                <my:ItemRowUserControl ItemName="{Binding ItemNameToBeSureWhatPropertyIsBound, Converter={StaticResource MyDummyConverter}}"  />
                <!--<Grid Background="Pink">
                    <TextBlock Text="{Binding ItemNameToBeSureWhatPropertyIsBound, Converter={StaticResource MyDummyConverter}}" Foreground="Black" Height="30" />
                </Grid>-->
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

    <Grid Grid.Row="1">
        <my:ItemRowUserControl ItemName="{Binding DataContext.ExampleItem.ItemNameToBeSureWhatPropertyIsBound, ElementName=MyWindow, Converter={StaticResource MyDummyConverter}}" />
    </Grid>
</Grid>

现在,如果我绑定到自定义的ItemRowUserControl,则进入转换器(在“调试输出”中看到的值)的值就是ItemRowUserControl本身。但是,如果我绑定注释掉的代码,一切都会很好。为什么会这样,如何对DataTemplate进行自定义控件,以使绑定(由Intellisense提供)可以正常工作?在侧面说明:绑定到网格第1行(位于底部)中的ItemRowUserControl可以正常工作,因此我猜想控件是否设置为可以正常工作?


阅读 277

收藏
2020-05-19

共1个答案

一尘不染

问题是您DataContext将UserControl的显式设置为其自身:

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

删除该分配并编写如下ItemName绑定:

<TextBlock Text="{Binding ItemName,
    RelativeSource={RelativeSource AncestorType=UserControl}}"/>

或像这样

<TextBlock Text="{Binding ItemName, ElementName=ItemRowControl}"/>
2020-05-19