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

2023-12-23

我的绑定有问题DataTemplate基于定义的DataType in ItemsControl,当我想绑定到我的自定义用户控件.

为了演示目的,我创建了简单的物品类别例如,我有这样的项目集合:

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

In my 视图模型我创建了这样的集合,并将其公开(单独使用一项进行比较):

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 自定义用户控件定义如下:

<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 in 代码隐藏:

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 属性时,我正在这样做主窗口像这样(注意:我有虚拟转换器仅用于调试目的,返回值,仅此而已):

<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 进行自定义控制,以便绑定(由智能感知提供)能够工作?旁注:绑定到网格第 1 行(底部)中的 ItemRowUserControl 工作正常,所以我猜控件已设置为按预期工作?


问题是你明确设置了DataContext您的 UserControl 自身:

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

删除该分配并写入ItemName像这样绑定:

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

或者像这样

<TextBlock Text="{Binding ItemName, ElementName=ItemRowControl}"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

绑定到 ItemsControl 的 DataTemplate 内的自定义控件 的相关文章

随机推荐

  • 初学者 Unix shell 脚本问题

    我正在做一项由两部分组成的作业 首先 我们被要求创建一个名为 fileType sh 的 shell 脚本 它能够判断文件是 Windows ASCII 类型还是 其他类型 我已经完成了该部分 并将在下面显示它应该执行的操作的示例 file
  • React Native 中的 URI 与 URL

    在react native中可以这样做 const somePath https
  • 拖放图像视图不起作用

    My RelativeLayout有图像 我只是想让它在整个布局中可拖动 问题是每次我拖放时 它都会回到原始位置 这是我的 拖拽布局 xml
  • 将彩信标记为以编程方式读取

    是否有办法更新彩信 短信数据库以将消息从已读标记为未读 反之亦然 我尝试过使用 URI 但它们对我不起作用 下面的代码可以帮助我更新彩信是否被标记为已查看 要将其用于 SMS 消息 只需将以下 content mms 替换为 content
  • Mod 重写并传递 URL 作为参数

    我在重写 mod 时遇到了一个小问题 我的一个朋友正在编写一个允许您上传图像的脚本 我们想要做的是允许用户将域名附加到直接图像链接 并且脚本将从提供的 URL 检索图像 例如 如果图像位于 http www test com image j
  • SVG 填充子元素的宽度

    我希望我的容器 SVG 元素能够缩放 以适应其子组元素或在溢出时显示滚动条 我想知道是否有一个 css 属性可以做到这一点 例如 如果标记如下所示 div class wrapper style width 500px div
  • 如何使用伪类选择除第一个和最后一个之外的所有子级?

    在 CSS 中 对于下面所示的示例 如何才能将样式应用于除第一个和最后一个段落之外的所有段落 div class entry p p p p p p p p p p div 我已尝试以下方法来排除第一段 但这不起作用 div entry p
  • OpenCV 的 iPhone 6 相机校准

    我正在使用 OpenCV 开发 iOS 增强现实应用程序 我在创建相机投影矩阵以允许 OpenGL 叠加层直接映射到标记顶部时遇到问题 我觉得这是因为我的 iPhone 6 摄像头没有根据应用程序正确校准 我知道有 OpenCV 代码可以使
  • UIScrollView 覆盖我的子视图的平移手势识别器

    如果我有一个带有子视图的滚动视图 并且子视图有一个平移手势识别器 则滚动视图的平移手势覆盖子视图的平移 我认为我想要的是相反的 所以我拖动一个子视图 它将在滚动视图中平移 但如果我触摸另一个区域 滚动视图将像平常一样平移 有没有简单的方法来
  • 在 Silverlight 拖放中获取放置索引

    This article http themechanicalbride blogspot com 2009 10 silverlight drag drop support part 2 html展示如何对放置事件实现复制操作 我想做同样
  • 在不使用背景颜色的情况下向 HTML 表格单元格添加背景颜色?

    除了背景颜色样式属性之外 还有其他方法可以向表格单元格添加 背景 颜色吗 我有一些表格 其中包含以编程方式生成的文本内容和背景颜色 它们可能会自行更新 我想暂时突出显示某些单元格 想象一下移动的光标 理想情况下不会触及现有代码或干扰背景颜色
  • 如何在设计时打开 WPF 菜单?

    我正在 WPF 中设置菜单样式 并且希望看看它的外观 而无需启动应用程序来打开菜单 有没有办法在设计时保持菜单打开 以便我可以看到菜单项 以便我可以随时看到更改 我目前只有 Visual Studio 2010 可以使用 您可以设置 IsS
  • 绝对值函数“fabsf”给定“double”类型的参数,但具有“float”类型的参数,这可能会导致值截断?

    鉴于此代码示例 CGFloat a 1 CGFloat b 2 CGFloat c fabsf a b 当前的 Xcode beta 编译器给了我这个警告 Absolute value function fabsf given an arg
  • C++ 错误:“成员 Eng​​ine::x 不是类型名称”

    我正在构建一个标准的 4 函数计算器 并且尝试将两个数字作为用户输入的参数传递 在我的 Engine h 类中我已经声明了 float num1 num2 我有这个功能 float Add num1 num2 在这些参数中 num1 和 n
  • MongoDB 空字段或 true/false

    在 MongoDB 上 当我们有 草稿 是 否 已发布 是 否 等字段时 哪个是最好的策略 在所有记录中创建字段并输入 是 否 值 还是将字段放在存在的位置 posts id 1 text hello draft true id 2 tex
  • Azure 配额超出异常

    当向通知中心发送通知时 我收到以下异常 Microsoft ServiceBus Messaging QuotaExceededException 远程 服务器返回错误 禁止 最大数量 通知操作已达到或超过 实际 33360 允许的最大值
  • 如何从文件中删除重复项并写入同一个文件?

    我知道我的标题不太容易解释 但让我尝试在这里解释一下 我有一个文件名test txt其中有一些重复的行 现在 我想做的是删除那些重复的行 同时update test txt与新内容 test txt AAAA BBBB AAAA CCCC
  • Swift:将枚举值转换为字符串?

    给定以下枚举 enum Audience case Public case Friends case Private 我如何获取字符串 Public 来自audience下面常数 let audience Audience Public 获
  • 访问组合框值

    I have a combobox and a button that makes runs a query with the values it gets from combobox but it does not seem to get
  • 绑定到 ItemsControl 的 DataTemplate 内的自定义控件

    我的绑定有问题DataTemplate基于定义的DataType in ItemsControl 当我想绑定到我的自定义用户控件 为了演示目的 我创建了简单的物品类别例如 我有这样的项目集合 public class Item public