【发布时间】:2018-06-26 16:00:08
【问题描述】:
我试图将 ObservableCollection 绑定到两个 ItemsControl 控件,但实际上只有最后一个 ItemsControl 正在更新。
XAML:
<Border BorderThickness="2" BorderBrush="Red">
<StackPanel>
<Grid Margin="0 10 0 0">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ItemsControl Grid.Column="0" Tag="LeftSideItemsControl" ItemsSource="{Binding Items, Mode=OneWay}"/>
<ItemsControl Grid.Column="1" Tag="RightSideItemsControl" ItemsSource="{Binding Items, Mode=OneWay}"/>
</Grid>
</StackPanel>
</Border>
将项目添加到 ObservableCollection 的代码:
public partial class DiagramContainer : UserControl
{
public ObservableCollection<UIElement> Items { get; set; }
public DiagramContainer()
{
InitializeComponent();
DataContext = this;
Items = new ObservableCollection<UIElement>();
Items.Add(new Button() { Content = "TEST" });
Items.Add(new TextBox() { Text = "TEST" });
}
}
当我运行我的应用程序时,我得到以下结果:
右侧(第二列)的 ItemsControl 是更新的,第一列不更新。
【问题讨论】:
-
一个
UIElement只能有一个单亲;因此,它不能包含在多个控件中。如果Items是ObservableCollection<string>,则两个 ItemsControls 都将由 Binding 更新。 -
@FrankM 谢谢,这是有道理的。
-
ItemsSource 的源集合中根本不应该有 UIElement。相反,您应该声明一个适当的 ItemTemplate,其中包含绑定到数据项类的属性的控件。如果有不同类型的项,请使用适当的 DataType 值声明 DataTemplates,或设置 ItemsControl 的 ItemTemplateSelector。
标签: wpf data-binding observablecollection itemscontrol