Reputation: 175
Something strange is happening there.
I have an horizontal stackpanel containing 2 elements : two identical listboxes.
Here is the problematic snippet :
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:Uxmal.Views" x:Class="Uxmal.Views.MainWindow"
Title="Test title">
<StackPanel Orientation="Horizontal">
<ListBox ItemsSource="{Binding TestControls, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" />
<ListBox ItemsSource="{Binding TestControls, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" />
</StackPanel>
</Window>
The two listboxes are (or should be) absolutely identical. They are bound to the same data source, a collection of user controls.
The constructor of the window :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
testControls.Add(new XmlElementControl());
testControls.Add(new XmlElementControl());
testControls.Add(new XmlElementControl());
testControls.Add(new XmlElementControl());
}
private List<XmlElementControl> testControls = new List<XmlElementControl>(4);
public IEnumerable<XmlElementControl> TestControls { get { return testControls; } }
}
and the simplified XAML for the XmlElementControlclass
<UserControl x:Class="Uxmal.Views.XmlElementControl" 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"> <StackPanel Width="500" Height="80" Orientation="Horizontal" Background="Gray"/> </UserControl>
But on the result :
The right pane of the window should contain the same list as the left pane, but it's empty instead.
What is happening ?
Upvotes: 0
Views: 94
Reputation: 81243
Your approach is wrong, list should not contain UI elements instead it should contain data which needs to be bound to ListBox.
Problem is any UI component can be added only in single Visual tree, you cannot add it to two different Visual trees at same time. Here, in your case you are trying to add XmlElementControl
to two different ListBoxes which definitely won't work.
Say create this test collection which return only range of numbers.
public IEnumerable<int> TestCollection
{
get
{
return Enumerable.Range(1, 4);
}
}
and create ItemTemplate
in XAML to represent that data:
<ListBox ItemsSource="{Binding TestCollection,
RelativeSource= {RelativeSource FindAncestor,
AncestorType={x:Type local:MainWindow}}}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:XmlElementControl/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Declare local
namespace at window root level, pointing to XmlElementControl
namespace.
Upvotes: 1