2016-12-05 50 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}"/> 
相關問題