title: Bind WPF Command to ViewModel property in C# XAML
body: <p>I'm trying to build a generic <code>Command</code> that can access properties from my <code>ViewModel</code>. On my Window are several <code>TextBoxes</code>, each <code>TextBox</code>has a <code>Button</code> next to it. When the <code>Button</code> is clicked I show an <code>OpenFileDialog</code> and set the <code>Text</code> of the <code>TextBox</code> to the selected files path. The <code>TextBox</code>itself has a <code>Binding</code> to a property in the <code>ViewModel</code>. Currently this is implemented with a <code>Command</code> in the <code>ViewModel</code>. The <code>Buttons</code> all call the same <code>Command</code>but each <code>Button</code> has a its property <code>CommandParameter</code> set to the <code>TextBox</code> that will receive the filepath. The drawback of this is, that I need to cast the parameter from the <code>Command</code>execution to a <code>TextBox</code> and then set its <code>Text</code>property. My question is now, if I can't somehow bind my 'Command' to the same property the <code>TextBox</code>is bound to. Here is what I currently do:</p>
  
  <p><strong>XAML</strong></p>
  
  <pre><code>&lt;TextBox Text="{Binding SettingsPath}" x:Name="txtSettingsPath"&gt;&lt;/TextBox&gt;
  &lt;Button Command="{Binding OpenFile}" 
  CommandParameter="{Binding ElementName=txtSettingsPath}"&gt;...&lt;/Button&gt;
  </code></pre>
  
  <p><strong>C#</strong></p>
  
  <pre><code>public ICommand OpenFile
  {
      get
      {
          bool CanExecuteOpenFileCommand()
          {
              return true;
          }
  
          CommandHandler GetOpenFileCommand()
          {
              return new CommandHandler((o) =&gt;
              {
                  OpenFileDialog ofd = new OpenFileDialog();
                  ofd.Multiselect = false;
  
                  if (!string.IsNullOrEmpty(SettingsPath) &amp;&amp; File.Exists(settingsPath))
                  {
                      ofd.InitialDirectory = Path.GetDirectoryName(SettingsPath);
                  }
  
                  if(ofd.ShowDialog() == true)
                  {
                      if(o is TextBox txt)
                      {
                          txt.Text = ofd.FileName;
                      }
                  }
  
              }, CanExecuteOpenFileCommand);
          }
  
          return GetOpenFileCommand();
      }
  }
  </code></pre>
  
  <p>In the XAML I would like to have something like this:</p>
  
  <pre><code>&lt;TextBox Text="{Binding SettingsPath}"&gt;&lt;/TextBox&gt;
  &lt;Button Command="{Binding OpenFile}" 
  CommandParameter="{Binding SettingsPath}"&gt;...&lt;/Button&gt;
  </code></pre>