title: Binding to TextBlock Width property in MVVM
body: <p>I have a <code>TextBlock</code> control in my view, its <code>Width</code> depends on the <code>Text</code> property. </p>
  
  <p>I'm looking for some way to bind the TextBlocks <code>Width</code> to a property in my model,which will work as follows:</p>
  
  <ol>
  <li>The setting of the <code>Width</code> must be done automatically based on <code>Text</code></li>
  <li>In my button click I would like to retrieve the Width</li>
  </ol>
  
  <p>I've tried the code below, but it keeps the <code>Width</code> as 0 if I don't explicitly set it in the constructor of the view model.Tried <code>Mode=OneWayToSource</code> and <code>Mode=OneWay</code> but it made no difference, any suggestions?</p>
  
  <p><strong>View:</strong></p>
  
  <pre><code>&lt;Grid&gt;
      &lt;TextBlock Text="Some text" Width="{Binding TextWidth,Mode=OneWayToSource}" /&gt;
      &lt;Button Content="Show Width" Height="30" Width="90" Command="{Binding ShowTextWidth}" /&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p><strong>View model:</strong></p>
  
  <pre><code>public event PropertyChangedEventHandler PropertyChanged;
  
  public void OnPropertyChanged(string propertyName)
  {
      if (PropertyChanged != null)
          PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
  
  private DelegateCommand&lt;object&gt; showTextWidth;
  public DelegateCommand&lt;object&gt; ShowTextWidth
  {
      get { return showTextWidth; }
      set { showTextWidth = value; }
  }
  
  private double textWidth;
  public double TextWidth
  {
      get { return textWidth; }
      set 
      { 
          textWidth = value;
          OnPropertyChanged("TextWidth");
      }
  }
  
  public ViewModel()
  {
      //If I explicitly specify the width it works:
      //TextWidth = 100;
      ShowTextWidth = new DelegateCommand&lt;object&gt;(ShowWidth);
  }
  
  private void ShowWidth(object parameter)
  {
      MessageBox.Show(TextWidth.ToString());
  }
  </code></pre>
  
  <p>}</p>