70457

How can i receive a reference to a control in WPF (MVVM)?

In my WPF MVVM Project I have a button that triggers a function that should add a node to a xml and then set the focus to a textbox. My question is, how can i receive a reference to a control?

View:

<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(); }

Answer1:

<strong>Don't do it in the ViewModel.</strong> The ViewModel shouldn't know anything about the view.

You can do it in code-behind:

    <li>

    handle the TreeView.SelectedItemChanged event in code-behind, and update a SelectedItem property on the ViewModel (you could also do it with an attached behavior)

    </li> <li>

    to focus the TextBox, raise an event from the ViewModel and handle it in code-behind:

    </li> </ul>

    <strong>ViewModel:</strong>

    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); }

    <strong>Code-behind:</strong>

    // 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(); }

    Answer2:

    You could use the FocusManager.FocusedElement attached property to handle ensuring the TextBox receives focus.

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

    As for your second part (textBox.SelectAll()) you may have to work on a behavior or attached property of your own that handles the focusing and selecting in one fell swoop.

Recommend

  • Writing XML in loop c#
  • How to add home screen shortcut without launching app after installation
  • WPF TreeView and Disabled Item
  • JavaFX get access to a Tab or TabPane from a TabContent(Node)
  • Context Menu in TableView JAVAFX 2.1
  • How to fix “the server certificate is not configured properly with HTTP.SYS” on Windows 7?
  • C# InvokeRequired with property getter
  • Enable text box based on radio button selected
  • Nested mongoose populate with promises
  • Pending Intent triggered by Alarm Manager seems to fire right away
  • getting installed applications programmattically
  • c# parsing xml with and apostrophe throws exception
  • DataGrid: Help accessing a control defined in a CellEditingTemplate
  • Xml Deserialization - Merging two elements into a single List object
  • networkstream “cannot access a disposed object” when using newly created networkstream
  • Change Font Style (bold, Italic, bold italic) in C# [duplicate]
  • Binding a list with another list with WPF
  • how to UNSELECT row in a ttk.Treeview in tkinter
  • Swing - Get new component under mouseReleased
  • MVC3 Razor - ListBox pre-select not working
  • Set the selected item in dropdownlist in MVC3
  • ilmerge with a PFX file
  • Spring Data JPA custom method causing PropertyReferenceException
  • Can I display google adwords (AdView) in javafx on android
  • Validaiting emails with Net.Mail MailAddress
  • sending/ receiving email in Java
  • Cannot Parse HTML Data Using Android / JSOUP
  • JTable with a ScrollPane misbehaving
  • Bitwise OR returns boolean when one of operands is nil
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • sending mail using smtp is too slow
  • Checking variable from a different class in C#
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?