wpf 为 ItemsControl 绑定到 DataTemplate 内的自定义控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27834271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:49:48  来源:igfitidea点击:

Binding to custom control inside DataTemplate for ItemsControl

c#wpfdata-bindingcustom-controlsitemscontrol

提问by Janez Lukan

I have a problem with bindings for DataTemplatebased on defined DataTypein ItemsControl, when I want to bind to my custom user control.

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

For demonstration purposes, I've created simple Item classexample, where I have collection of items like this:

出于演示目的,我创建了简单的Item 类示例,其中包含如下项目的集合:

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

In my ViewModelI create such collection, and expose it (with one item for comparison separately):

在我的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));
    }
}

My custom user controlis defined like this:

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

<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>

...and it has one DependencyPropertyin code behind:

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

The problem is, when I try to bind to property of Item in DataTemplate for ItemsControl, which I'm doing in MainWindowlike this (note: I have dummy converter for debugging purposes only, returning value back, and nothing more):

问题是,当我尝试为 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>

Now, in case I bind to my custom ItemRowUserControl, the value I get into converter (and I see the same in Debug Output) is ItemRowUserControl itself. But if I bind to commented out code, everything works fine. Why is that, and how can I have custom control for DataTemplate so that bindings (offered by intellisense) will work? On the side note: binding to my ItemRowUserControl in grid row 1 (at the bottom) works fine, so I guess control is set to work as expected?

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

回答by Clemens

The problem is that you explicitly set the DataContextof your UserControl to itself:

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

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

Remove that assignment and write the ItemNamebinding like this:

删除该赋值并ItemName像这样编写绑定:

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

or like this

或者像这样

<TextBlock Text="{Binding ItemName, ElementName=ItemRowControl}"/>