我有一个按钮,点击按钮会打开一个弹出窗口,里面有一个列表框。列表框中的项目是模板化的,模板包含日期选择器和2个文本框,用于输入日期,小时和分钟。
我面临的问题是这个 - 我在我的日期选择器或文本框上做的事情,除非我以某种方式明确地点击控件上的空格,否则列表框项目不会得到焦点。问题是 - 当点击/聚焦datatemplate中的任何控件时,如何将列表框项设置为选定项?请注意,我关注MVVM。
代码:
列表框:
<ListBox x:Name="AsOfList" SelectedItem="{Binding SelectedAsOfDate}" ItemsSource="{Binding Path=AsOfDates}"/>
的DataTemplate:
<DataTemplate DataType="{x:Type Domain:UserDefinedDate}">
<DatePicker DockPanel.Dock="Left" Name="AsOfDate" Width="115" SelectedDate="{Binding SelectedDate,
UpdateSourceTrigger=PropertyChanged}" SelectedDateFormat="Short" FirstDayOfWeek="Monday" />
</DataTemplate>
按钮:
<Button Grid.Row="1" Grid.Column="1" Height="25" HorizontalAlignment="Center" VerticalAlignment="Center" Name="SelectedDate" Click="SelectedDate_Click"
ToolTip="{Binding Path=AsOfDateViewModel.ToolTip}">
<Button.Content>
<DockPanel>
<TextBlock Text="{Binding Path=AsOfDateViewModel.DisplayText}" />
<Image Height="10" Width="10" Source="Down.png" />
</DockPanel>
</Button.Content>
</Button>
弹出窗口:
<Popup x:Name="DateSelectorPopUp" PlacementTarget="{Binding ElementName=SelectedDate}" StaysOpen="False"
IsOpen="{Binding Path=AsOfDateViewModel.IsOpen}" >
<Views:AsOfDateSelector Width="Auto" DataContext="{Binding Path=AsOfDateViewModel}"/>
</Popup>
答案 0 :(得分:0)
在BooleanAnimationUsingKeyFrames
上触发IsSelected
时,您可以启动GotKeyboardFocus
动画来设置ListBoxItem
:
<ListBox x:Name="AsOfList" SelectedItem="{Binding SelectedAsOfDate}" ItemsSource="{Binding Path=AsOfDates}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<EventTrigger RoutedEvent="GotKeyboardFocus">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
</ListBox.ItemTemplate>
</ListBox>