如何通过XAML设置`myListView`的值?

时间:2012-11-19 11:52:03

标签: wpf xaml

我定义了自己的控件 - NameInfoControl,它基于UserControl彻底的XAML:

<UserControl x:Class="AcadLoadManager.NameInfoControl"
             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" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <ToolBar>
                <Button x:Name="btnAdd" x:FieldModifier="public" ToolTip="Add record" >
                    <Image Source="/AcadLoadManager;component/Icons/bullet_sparkle.png" Width="16"/>
                </Button>
                <Button x:Name="btnEdit" x:FieldModifier="public" ToolTip="Edit record">
                    <Image Source="/AcadLoadManager;component/Icons/bullet_edit.png" Width="16"/>
                </Button>
                <Button  x:Name="btnRemove" x:FieldModifier="public" ToolTip="Remove record">
                    <Image Source="/AcadLoadManager;component/Icons/bullet_cross.png" Width="16"/>
                </Button>
            </ToolBar>
            <ListView x:Name="myListView" x:FieldModifier="public" Margin="3" Grid.Row="1">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Width="100" Header="Global name" 
                                        DisplayMemberBinding="{Binding GlobalName}"/>
                        <GridViewColumn Width="100" Header="Local name" 
                                        DisplayMemberBinding="{Binding LocalName}"/>
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>
    </Grid>
</UserControl>

看起来如此:

enter image description here

我的控件有ListView项,名为 myListView 。如何通过XAML为ItemsSource实例设置 myListView NameInfoControl属性的值?我需要在下一个代码中使用它:

<GroupBox Header="Command groups:" Grid.Column="0" Grid.Row="1" Margin="5">
    <local:NameInfoControl/>
</GroupBox>

1 个答案:

答案 0 :(得分:1)

在您的NameInfoControl的XAML中,将myListView的项目绑定到您控件的DataContext

<ListView ItemsSource="{Binding}" x:Name="myListView" x:FieldModifier="public" Margin="3" Grid.Row="1">

然后在使用该控件的父XAML中将DataContext绑定到包含应显示的项的列表:

<local:NameInfoControl DataContext="{Binding MyCollectionOfItems}" />