数据绑定- WPF:在UserControl中绑定ListView时不显示任何项



我很确定这是一个UserControl DataContext问题,但我只是没有看到它:

这是我的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>

这是后面的代码:

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( ) );
    }
}

在运行时,Map有8个项目,但在ListView中没有显示任何内容。在一个独立的测试应用程序中,它与DataContext="{Binding RelativeSource={RelativeSource Self}}"一起工作,但作为UserControl,这不起作用。如上所述,我甚至尝试在构造函数中设置DataContext = this

谢谢!

我从来没有弄清楚如何在XAML中设置DataContext,但是我通过做以下事情来工作:

在XAML中,我将x:Name="listview"添加到ListView中。

然后,在后面的代码中,我将属性Map转换为DependencyProperty

public ObservableCollection<KeyValuePair<string, string>> Map
{
    get { return (ObservableCollection<KeyValuePair<string, string>>)GetValue( MapProperty ); }
    set { SetValue( MapProperty, value ); }
} 
public static DependencyProperty MapProperty = DependencyProperty.Register( "Map",
     typeof( ObservableCollection<KeyValuePair<string, string>> ), 
     typeof( DetailsBox ),
     new PropertyMetadata( new ObservableCollection<KeyValuePair<string, string>>( ) ) );

DataContext = this;从构造函数中移除,并在加载Map后将listview.DataContext = Map;添加到Initialize。

最新更新