问题
I have a ListView
named MeditationDiaryListView
with two columns and two headers. I have the width of the DataTemplate
in the listview equal to the width of 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>
Unfortunately, when I assign new values to the property in the ItemsSource
binding the ListView
becomes empty. If I remove the Width="{Binding ActualWidth, ElementName=MeditationDiaryListViewHeaders}
part from the ListView
this does not happen, but then the width is not equal to the parent.
How can I both have the width equal to the parent and be able to update the contents of the ItemsSource
of the MeditationDiaryListView
?
回答1:
Remove the Width
in your DataTemplate
and set the item container width to Stretch
on your 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>
Your ListView
and your header Grid
should now have the same width because of their parent container.
来源:https://stackoverflow.com/questions/33173892/how-to-bind-datatemplate-width-to-parent-and-be-able-to-update-viewmodel-propert