2016-08-04 76 views
1

在UWP应用程序(Windows 10)上,我在ListView中显示记录列表。如何在ListView项目的TextBox中设置焦点?

当我点击一个项目时,它的StackPanel显示(使用INotifyPropertyChanged)。 在StackPanel中,有一个带有通过绑定填充的一些数据的文本框。

我希望当StackPanel变得可见时TextBox会自动接收焦点,但是我找不到要使用的属性或事件以及如何触发textBox.Focus()。

感谢您对此的反馈!

的DataTemplate中:

<DataTemplate x:Key="templateList"> 
     <StackPanel> 
... 
      <StackPanel Visibility="{Binding IsSelected}"> 
       <TextBox x:Name="textBox" 
         Text="{Binding Title, Mode=TwoWay}"/> 
... 
      </StackPanel> 
     </StackPanel> 
    </DataTemplate> 
... 

ListView控件:

<ListView x:Name="listView" 
      ItemsSource="{Binding mylist}" 
      ItemTemplate="{StaticResource templateList}"/> 

回答

2

我可以建议针对这种情况使用Behaviors。正如我注意到的,您使用Visibility类型为IsSelected属性。这意味着我们可以使用DataTriggerBehavior和创造我们SetupFocusAction其实现IAction

public class SetupFocusAction : DependencyObject, IAction 
{ 
    public Control TargetObject 
    { 
     get { return (Control)GetValue(TargetObjectProperty); } 
     set { SetValue(TargetObjectProperty, value); } 
    } 

    public static readonly DependencyProperty TargetObjectProperty = 
     DependencyProperty.Register("TargetObject", typeof(Control), typeof(SetupFocusAction), new PropertyMetadata(0)); 

    public object Execute(object sender, object parameter) 
    { 
     return TargetObject?.Focus(FocusState.Programmatic); 
    } 
} 

之后,我们可以在XAML中使用这个动作:

xmlns:i="using:Microsoft.Xaml.Interactivity" 
xmlns:core="using:Microsoft.Xaml.Interactions.Core" 

... 

<StackPanel Visibility="{Binding IsSelected}" 
      Grid.Row="1"> 
    <TextBox x:Name="textBox" 
       Text="{Binding Title, Mode=TwoWay}"> 
     <i:Interaction.Behaviors> 
      <core:DataTriggerBehavior Binding="{Binding IsSelected}" 
             ComparisonCondition="Equal" 
             Value="Visible"> 
       <local:SetupFocusAction TargetObject="{Binding ElementName=textBox}"/> 
      </core:DataTriggerBehavior> 
     </i:Interaction.Behaviors> 
    </TextBox> 
</StackPanel> 

enter image description here

+0

此非常感谢!我一直在尝试,但为C#部分获取以下错误:CS0246 \t无法找到类型或命名空间名称'IAction'(缺少using指令还是程序集引用?)。我应该包括哪些使用指令?我是否需要添加特定参考才能使用行为? – Daniel

+0

您可以通过[Nuget]添加库(https://www.nuget.org/packages/Microsoft.Xaml.Behaviors.Uwp.Managed/) –

+0

我为我的项目安装了Template10库,并且所有工作都按预期工作!再次感谢你的帮助 :-) – Daniel