如何将DataTemplate宽度绑定到父级并能够更新viewmodel属性?

时间:2015-10-16 15:13:06

标签: c# xaml windows-phone-8.1

我有一个名为ListView的{​​{1}},其中包含两列和两个标题。我将listview中MeditationDiaryListView的宽度等于DataTemplate的宽度:

MeditationDiaryListViewHeaders

不幸的是,当我在<Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <Grid Name="MeditationDiaryListViewHeaders"> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="Start time" FontSize="16" /> <TextBlock Grid.Column="1" Text="Time meditated" FontSize="16" /> </Grid> <ListView Grid.ColumnSpan="2" Grid.Row="1" Name="MeditationDiaryListView" ItemsSource="{Binding MeditationDiary}"> <ListView.ItemTemplate> <DataTemplate> <Grid Width="{Binding ActualWidth, ElementName=MeditationDiaryListViewHeaders}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding StartTime}" Grid.Column="0" /> <TextBlock Text="{Binding TimeMeditated}" Grid.Column="1" /> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView> 绑定中为属性分配新值时,ItemsSource变为空。如果我从ListView移除Width="{Binding ActualWidth, ElementName=MeditationDiaryListViewHeaders}部分,则不会发生这种情况,但宽度不等于父级。

我如何才能使宽度等于父级,并且能够更新ListView的{​​{1}}的内容?

1 个答案:

答案 0 :(得分:1)

删除Width中的DataTemplate并将项目容器宽度设置为Stretch上的ListView

<ListView 
    Grid.ColumnSpan="2"
    Grid.Row="1"
    x:Name="MeditationDiaryListView" 
    ItemsSource="{Binding MeditationDiary}"
    HorizontalAlignment="Stretch"
    HorizontalContentAlignment="Stretch">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*" />
                    <ColumnDefinition Width="1*" />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding StartTime}" 
                            Grid.Column="0" />
                <TextBlock Text="{Binding TimeMeditated}" 
                            Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

由于其父容器,您的ListView和标题Grid现在应具有相同的宽度。