【发布时间】:2025-11-29 02:55:02
【问题描述】:
我有一个 WPF UserControl 包装了一些其他控件。其中之一是ItemsControl,我需要在ItemsControl 的Items 属性中提供UserControl,所以我做了以下操作:
public partial class MyControl : UserControl
{
private static readonly DependencyPropertyKey PagesPropertyKey = DependencyProperty.RegisterReadOnly("Pages", typeof(ObservableCollection<XXX>), typeof(MyControl), new FrameworkPropertyMetadata(new ObservableCollection<XXX>()));
public static DependencyProperty PagesProperty = PagesPropertyKey.DependencyProperty;
public ObservableCollection<XXX> Pages
{
get { return (ObservableCollection<XXX>) base.GetValue(PagesProperty); }
set { base.SetValue(PagesProperty, value); }
}
}
然后在 XAML 中 ItemsControl 具有以下内容:
ItemsSource="{Binding Pages, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:TypeExtension views1:MyControl}}}"
我认为这应该可以工作,实际上使用 Snoop 查找 UserControl 和 ItemsControl 具有相同的元素,但是当我直接将元素添加到内部 ItemsControl 时,我添加的第一个元素会自动选择,当我使用我的UserControl 执行此操作没有发生任何选择,所以出了点问题。
有什么想法吗?
编辑:该控件是一个向导控件,因为我们总是将它与周围的一些其他控件一起使用,所以我正在创建一个新的用户控件。如果我在 View 中直接使用 Wizard 自动选择 ItemsSource gest 的第一项,如果我将 Wizard 的 ItemsSource 设置为 Pages 属性,则启动时没有选择页面。
我真的很想知道为什么会这样。
【问题讨论】:
-
您可以选择从
ItemsControl派生而不仅仅是UserControl -
@Vignesh.N:我有几个控件要显示,它们不是 ItemsControl 的一部分。 ItemsControl 会尝试像 ListBox 一样绘制所有内容,不是吗?
标签: c# wpf data-binding binding user-controls