2016-08-04 52 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

相關問題