I’m pretty sure this is a UserControl DataContext problem, but I am just not seeing it:
This is my XAML:
<UserControl x:Class="WFT.Controls.DetailsBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wft="clr-namespace:WFT.Controls" >
<wft:CaptionedBox Caption="Details" Margin="1" >
<ListView ItemsSource="{Binding Map}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Key}" />
<GridViewColumn DisplayMemberBinding="{Binding Value}" />
</GridView>
</ListView.View>
</ListView>
</wft:CaptionedBox>
</UserControl>
This is the code-behind:
public partial class DetailsBox : UserControl
{
ObservableCollection<KeyValuePair<string, string>> m_Map =
new ObservableCollection<KeyValuePair<string, string>>( );
public ObservableCollection<KeyValuePair<string, string>> Map
{ get { return m_Map; } }
public DetailsBox( )
{
InitializeComponent( );
DataContext = this;
}
public void Initialize( List<string> map )
{
IEnumerable<int> range = Enumerable.Range( 0, map.Count );
m_Map = new ObservableCollection<KeyValuePair<string, string>>(
range.Where( r => 0 == r % 2 && map[ r + 1 ].Trim( ) != "N/A" )
.Select( r => new KeyValuePair<string, string>( map[ r ], map[ r + 1 ] ) ).ToList( ) );
}
}
At run-time, Map has eight items, but nothing shows in the ListView. In a stand-alone test app, it works with DataContext="{Binding RelativeSource={RelativeSource Self}}", but as a UserControl, that didn’t work. I have even resorted, as you see above, to attempting to set DataContext = this in the constructor.
Thanks!
I never did figure out how to set the DataContext in the XAML, but I got things to work by doing the following:
In the XAML, I added
x:Name="listview"to the ListView.Then, in the code behind, I turned the property, Map, into a DependencyProperty
removed
DataContext = this;from the constructor, and addedlistview.DataContext = Map;to Initialize, after loading Map.