我有一个ListView,里面有一堆人,支持多项选择。我希望拥有它,以便当通过复选框选择一个人时,会出现其他控件 - 在本例中,包含一些 TimePicker 控件的 StackPanel 变得可见。
当取消选择此人时,StackPanel 应恢复为不可见。
我当前的代码:
XAML:
<ContentDialog.Resources>
<DataTemplate x:Key="ContactListViewTemplate" x:DataType="model:Client">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Ellipse x:Name="Ellipse"
Grid.RowSpan="2"
Width ="32"
Height="32"
Margin="6"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Fill="{ThemeResource SystemControlBackgroundBaseMediumBrush}"/>
<TextBlock Grid.Column="1"
Text="{x:Bind FirstName}"
x:Phase="1"
Style="{ThemeResource BaseTextBlockStyle}"
Margin="12,6,0,0"/>
<TextBlock Grid.Column="1"
Grid.Row="1"
Text="{x:Bind LastName}"
x:Phase="2"
Style="{ThemeResource BodyTextBlockStyle}"
Margin="12,0,0,6"/>
<StackPanel Orientation="Horizontal" x:Name="timePanel" Grid.Column="2" Grid.RowSpan="2" Visibility="Collapsed">
<TimePicker Header="Start"></TimePicker>
<TimePicker Header="End"></TimePicker>
</StackPanel>
</Grid>
</DataTemplate>
</ContentDialog.Resources>
<ListView x:Name="clientsList" SelectionMode="Multiple" ItemTemplate="{StaticResource ContactListViewTemplate}" SelectionChanged="ClientsList_SelectionChanged" />
背后代码:
private void ClientsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Debug.WriteLine("called mett " + e.AddedItems.Count);
var listView= sender as ListView;
if(e.RemovedItems.Count > 0)
{
}
if(e.AddedItems.Count > 0)
{
foreach(var item in e.AddedItems)
{
ListViewItem myListViewItem = (ListViewItem)item;
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListViewItem);
StackPanel stackPanel = myContentPresenter.ContentTemplate.FindDescendant("timePanel") as StackPanel;
}
}
}
让我向您展示一种方法,即使用
timePanel上的
Loaded
事件来实现此目的。
private void TimePanel_Loaded(object sender, RoutedEventArgs e)
{
if (sender is not StackPanel timePickersContainer ||
timePickersContainer.FindAscendant<ListView>() is not ListView listView ||
timePickersContainer.DataContext is not object dataContext ||
listView.ContainerFromItem(dataContext) is not ListViewItem listViewItem)
{
return;
}
timePickersContainer.SetBinding(
VisibilityProperty,
new Binding
{
Source = listViewItem,
Path = new PropertyPath("IsSelected"),
Mode = BindingMode.OneWay,
Converter = new TrueToVisibleConverter(),
});
}