尽管我怀疑可能有更好的方法来解决您的问题,但我想我对您想要做的事情有一个答案。(您没有提到您的容器是什么类型。例如 StackPanel 会为您处理宽度计算。请参阅下面的 TextBox#2)
首先是 XAML
<Window x:Class="WpfApplication1.Window2" ...
xmlns:local="clr-namespace:WpfApplication1"
Title="Window2" Height="300" Width="300">
<Window.Resources>
<local:WidthSansMarginConverter x:Key="widthConverter" />
</Window.Resources>
<Grid>
<StackPanel x:Name="stack">
<TextBlock x:Name="txtStatusMessages"
Width="{Binding ElementName=stack,Path=ActualWidth,
Converter={StaticResource widthConverter}}"
TextWrapping="WrapWithOverflow"
Background="Aquamarine"
Margin="5,5,5,5">
This is a message
</TextBlock>
<TextBlock x:Name="txtWhatsWrongWithThis"
TextWrapping="WrapWithOverflow"
Background="Aquamarine"
Margin="5,5,5,5">
This is another message
</TextBlock>
</StackPanel>
</Grid>
</Window>
接下来是转换器。我们这里有一个问题.. 因为Convert 方法的 ConverterParameter由于某种原因不能是动态值。因此,我们通过在 Window 的 ctor 中设置的 Converter 的公共属性潜入 Textbox Margin。
WidthSansMarginConverter.cs
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 < 0 ? 0 : dAdjustedWidth);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Window2.xaml.cs
public Window2()
{
InitializeComponent();
WidthSansMarginConverter obConverter = this.FindResource("widthConverter") as WidthSansMarginConverter;
obConverter.Margin = txtStatusMessages.Margin;
}
HTH。谢谢你的练习:)