2011-04-08 15 views
2

私のWPF MVVMプロジェクトでは、XMLにノードを追加し、フォーカスをテキストボックスに設定する関数をトリガーするボタンがあります。 私の質問は、どのようにコントロールへの参照を受け取ることができますか?WPF(MVVM)でコントロールへの参照を受け取る方法はありますか?

ビュー:

<Button Command="{Binding Path=ButtonAddCategory_Click}" /> 

のViewModel:

RelayCommand buttonAddCategory_Click; 
public ICommand ButtonAddCategory_Click 
{ 
    get 
    { 
     return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(), 
                         param => true)); 
    } 
} 

public void AddCategory() 
{ 
    ... 
    //get the "node" -> reference? 
    XmlNode selectedItem = (XmlNode)treeView.SelectedItem; 
    .. 
    //add the node to the xml 
    .. 
    //change focus -> reference? 
    textBoxTitel.Focus(); 
    textBoxTitel.SelectAll(); 
} 
+0

TreeViewsは残念ながらMVVMでうまくいきません... – Will

+0

実際にはMVVMでうまくプレイできますが、少し作業が必要です... SelectedItemをバインドします。参照してください[この記事](http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx)Josh Smith –

+0

@ ThomasLevesque:lurl、私は他のコントロールと同じ能力を得るために少しの作業を行います箱から出てきても、いい演奏として私を叩くことはありません。 – Will

答えて

3

のViewModelにそれをしないでください。 ViewModelはについては何も知らないはずです。

(あなたはまた、付属の行動でそれを行うことができます)

  • はコードビハインドでTreeView.SelectedItemChangedイベントを処理し、ビューモデルにSelectedItemプロパティを更新します。

    あなたは、コードビハインドでそれを行うことができます

  • のViewModelからイベントを発生させ、コードビハインドでそれを処理、TextBoxを集中させる:

のViewModel:

public XmlNode SelectedItem { get; set; } 

public event EventHandler FocusTitle; 

public void AddCategory() 
{ 
    ... 
    //get the "node" -> reference? 
    XmlNode selectedItem = this.SelectedItem; 
    .. 
    //add the node to the xml 
    .. 
    // Notify the view to focus the TextBox 
    if (FocusTitle != null) 
     FocusTitle(this, EventArgs.Empty); 

} 

コードビハインド:

// ctor 
public MyView() 
{ 
    InitializeComponent(); 
    DataContextChanged += MyView_DataContextChanged; 
} 

private void MyView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) 
{ 
    MyViewModel vm = (MyViewModel)e.NewValue; 
    vm.FocusTitle += ViewModel_FocusTitle; 
} 

private void TreeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventHandler<Object> e) 
{ 
    MyViewModel vm = (MyViewModel)DataContext; 
    vm.SelectedItem = (XmlNode)e.NewValue; 
} 

private void ViewModel_FocusTitle(object sender, EventArgs e) 
{ 
    textBoxTitle.Focus(); 
} 
+0

偉大な例、私を助けて、thx! – jwillmer

1

あなたはTextBoxがフォーカスを受け取る確保処理するためにFocusManager.FocusedElement添付プロパティを使用することができます。あなたが集中して一挙に選択を扱う行動したり、独自の添付プロパティで作業する必要があり、あなたの第二部(textBox.SelectAll())については

<DataTemplate DataType="{x:Type YourViewModel}"> 
    <Grid FocusManager.FocusedElement="{Binding ElementName=userInput}"> 
     <TextBox x:Name="userInput" /> 
    </Grid> 
</DataTemplate> 

関連する問題