C# 如何在ListView项目的文本框中设置焦点?
在UWP应用程序(Windows 10)上,我正在列表视图中显示记录列表 单击项目时,将显示其StackPanel(使用INotifyPropertyChanged)。 在StackPanel中,有一个文本框,其中包含一些通过绑定填充的数据 我希望每当StackPanel可见时,TextBox自动接收焦点,但我找不到要使用的属性或事件,以及如何触发TextBox.focus() 谢谢你的反馈 数据模板:C# 如何在ListView项目的文本框中设置焦点?,c#,listview,uwp,setfocus,C#,Listview,Uwp,Setfocus,在UWP应用程序(Windows 10)上,我正在列表视图中显示记录列表 单击项目时,将显示其StackPanel(使用INotifyPropertyChanged)。 在StackPanel中,有一个文本框,其中包含一些通过绑定填充的数据 我希望每当StackPanel可见时,TextBox自动接收焦点,但我找不到要使用的属性或事件,以及如何触发TextBox.focus() 谢谢你的反馈 数据模板: ... ... ... 列表视图: 我可以建议在这种情况下使用行为。正如我所注意到的,您
...
...
...
列表视图:
我可以建议在这种情况下使用
行为。正如我所注意到的,您为IsSelected
属性使用Visibility
类型。这意味着我们可以使用DataTriggerBehavior
并创建我们的SetupFocusAction
,它实现iaAction
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>
xmlns:i=“使用:Microsoft.Xaml.Interactivity”
xmlns:core=“使用:Microsoft.Xaml.Interactions.core”
...
非常感谢!我一直在尝试,但C#part出现以下错误:CS0246找不到类型或命名空间名称“IAction”(是否缺少using指令或程序集引用?)。我应该包括哪个使用指令?我是否需要添加特定的引用才能使用行为?您可以通过我为我的项目安装Template10 library来添加库,并且一切正常!再次感谢您的帮助:-)
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);
}
}
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>