2017-02-02 3 views
0

selectedMaxel에 바인딩 된 selectedIndex가있는 listview가 있습니다. ViewModel이 selectedIndex를 변경할 때 listview가 새 항목을 선택합니다. 불행하게도이 항목에 집중하지 않고 많은 항목이 목록에 있으면 사용자에게 성가 시게됩니다.바인딩으로 인해 selectedIndex가 변경된 경우 선택된 ListViewItem에 포커스를 설정합니다.

XAML을 사용하거나 적어도 MVVM을 사용하여 selectedItem에 포커스를 변경하려면 어떻게해야합니까?

<ListView ItemsSource="{Binding allTags}" ItemTemplate="{StaticResource listTemplate}" 
      SelectedIndex="{Binding selectedIndex}"> 
</ListView> 

답변

1

당신이 할 수 있었던 TextBox 초점을 첨부 동작을 사용 :

public static class FocusExtension 
{ 
    public static bool GetIsFocused(TextBox textBox) 
    { 
     return (bool)textBox.GetValue(IsFocusedProperty); 
    } 

    public static void SetIsFocused(TextBox textBox, bool value) 
    { 
     textBox.SetValue(IsFocusedProperty, value); 
    } 

    public static readonly DependencyProperty IsFocusedProperty = 
     DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusExtension), 
      new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); 

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     TextBox textBox = d as TextBox; 
     if ((bool)e.NewValue) 
     { 
      textBox.Dispatcher.BeginInvoke(new Action(()=> 
      { 
       Keyboard.Focus(textBox); 
      }), DispatcherPriority.Background); 
     } 
    } 
} 

보기 :

<Window.DataContext> 
    <local:TestWindowViewModel></local:TestWindowViewModel> 
</Window.DataContext> 

<Window.Resources> 
    <DataTemplate x:Key="template"> 
     <TextBox x:Name="listItemTextBox"> 
      <TextBox.Style> 
       <Style TargetType="TextBox"> 
        <Style.Triggers> 
         <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListViewItem}}" Value="True"> 
          <Setter Property="local:FocusExtension.IsFocused" Value="True" /> 
         </DataTrigger> 
        </Style.Triggers> 
       </Style> 
      </TextBox.Style> 
     </TextBox> 
    </DataTemplate> 
</Window.Resources> 

<StackPanel> 
    <ListView ItemsSource="{Binding myList}" ItemTemplate="{StaticResource template}" SelectedIndex="{Binding SelectedIndex}"></ListView> 
</StackPanel> 

보기 모델 :

public class TestWindowViewModel : INotifyPropertyChanged 
{ 
    public List<string> myList { get; set; } 

    private int _selectedIndex; 

    public int SelectedIndex 
    { 
     get { return _selectedIndex; } 
     set { _selectedIndex = value; } 
    } 


    public TestWindowViewModel() 
    { 
     myList = new List<string> { "one", "two", "three" }; 
     SelectedIndex = 1; 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
}