2016-12-05 51 views
0

我在我的C#/ WPF应用程序中有一个xaml屏幕,它具有组合框(ProductType)和文本框(ProductCode)。 第一次加载屏幕时,我使用下面的代码设置了此文本框的焦点及其工作正常。 我还需要在用户更改comboxbox中的值时设置焦点,但似乎不起作用。将焦点放在文本框中,以改变下拉值

我在这里错过了什么? (注:我的第一选择将是实现这一使用MVVM设计的解决方案pattern.If它不工作,我想出去代码隐藏的方法吧。)

MainWindowResources.xaml

<Style TargetType="TextBox" x:Key="ProductCodeStyle"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding FocusOnProductCode}" Value="True"> 
       <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" /> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 

MainWindow.xaml:

<TextBox Name="txtProductCode" HorizontalAlignment="Left" Height="22" TextWrapping="Wrap" Text="{Binding ProductCodeValue, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged }" 
         VerticalAlignment="Top" Width="165" Style="{DynamicResource ProductCodeStyle}" Grid.Column="3" Margin="1,2,0,0" TabIndex="0" IsHitTestVisible="True"/> 

MainWindowViewModel.cs

public MainWindowViewModel(MainWindow window) 
{ 

this.FocusOnProductCode = true; 
} 


public ProductType SelectedProductType 
     { 
      get 
      { 
       return m_selectedProductType; 
      } 
      set 
      {     
       m_selectedProductType = value; 

       this.FocusOnProductCode = true; 

      } 
     } 



     public bool FocusOnProductCode 
     { 
      get { return m_focusOnProductCode; } 
      set 
      { 
       m_focusOnProductCode;= value; 
       OnPropertyChanged("FocusOnProductCode"); 
       OnPropertyChanged("SelectedProductType"); 
      } 
     } 

谢谢。

+1

设置焦点是UI的关注。只需在窗口代码后面观看组合框,并根据需要设置焦点。 – Will

+0

谢谢@ Will.But我想看看是否有任何解决方案使用MVVM设计模式。已更新我的问题相同。 –

+0

使您的UI在代码隐藏*中工作*使用MVVM设计模式。将Shoehorning UI工作到您的ViewModel是MVVM设计模式的确切*相反*。不要难过 - 欢欣鼓舞!只需几分钟和几行代码即可解决此问题!你会坚持这种模式!这是双赢的! – Will

回答

0

通过在运行时动态设置StyleManager中的FocusManager.FocusedElement附加属性,将焦点放在纯XAML中的元素将不起作用,但您可以使用行为来设置指示该元素是否应该聚焦的布尔属性在如下面的线程所建议的视图模型类:

Set focus on textbox in WPF from view model (C#)

How to set Focus to a WPF Control using MVVM?

<TextBox Name="txtProductCode" Text="{Binding ProductCodeValue, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" local:FocusExtension.IsFocused="{Binding FocusOnProductCode}"/> 
相关问题