Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Although I suspect there may be a better way to solve your problem, I think I have an answer for what you want to do. ( You didn't mention what type your container is. A StackPanel for instance takes care of the width calculation for you. See TextBox#2 below)</p> <p>First the XAML</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window2" ... xmlns:local="clr-namespace:WpfApplication1" Title="Window2" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;local:WidthSansMarginConverter x:Key="widthConverter" /&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;StackPanel x:Name="stack"&gt; &lt;TextBlock x:Name="txtStatusMessages" Width="{Binding ElementName=stack,Path=ActualWidth, Converter={StaticResource widthConverter}}" TextWrapping="WrapWithOverflow" Background="Aquamarine" Margin="5,5,5,5"&gt; This is a message &lt;/TextBlock&gt; &lt;TextBlock x:Name="txtWhatsWrongWithThis" TextWrapping="WrapWithOverflow" Background="Aquamarine" Margin="5,5,5,5"&gt; This is another message &lt;/TextBlock&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>Next the Converter. We have a problem here.. since <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7298ceb5-bf56-47aa-a161-5dd99189408b/" rel="nofollow noreferrer">the ConverterParameter for the Convert methods cannot be a dynamic value</a> for some reason. So we sneak in the Textbox Margin via a public property of the Converter that we set in Window's ctor. <strong>WidthSansMarginConverter.cs</strong> </p> <pre><code>public class WidthSansMarginConverter : IValueConverter { private Thickness m_Margin = new Thickness(0.0); public Thickness Margin { get { return m_Margin; } set { m_Margin = value; } } #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(double)) { return null; } double dParentWidth = Double.Parse(value.ToString()); double dAdjustedWidth = dParentWidth-m_Margin.Left-m_Margin.Right; return (dAdjustedWidth &lt; 0 ? 0 : dAdjustedWidth); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } </code></pre> <p>Window2.xaml.cs</p> <pre><code> public Window2() { InitializeComponent(); WidthSansMarginConverter obConverter = this.FindResource("widthConverter") as WidthSansMarginConverter; obConverter.Margin = txtStatusMessages.Margin; } </code></pre> <p>HTH. Thanks for the exercise :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload