如果您没有明确设置宽度/高度,则必须在后面的代码中使用 ActualWidth 和 ActualHeight。
Line1.X1 = Grid1.ActualWidth / 2; Line1.Y1 = Grid1.ActualHeight / 2;
如果你想在 XAML 中做,你可以让 BindingConverters 对绑定的值执行逻辑。
xml:
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication6"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:DivideByConverter x:Key="Divider" />
</Window.Resources>
<Grid x:Name="LayoutRoot">
<Line Name="Line1" X2="{Binding ElementName=LayoutRoot, Path=ActualWidth, Converter={StaticResource ResourceKey=Divider}}" Y2="{Binding ElementName=LayoutRoot, Path=ActualHeight, Converter={StaticResource ResourceKey=Divider}}" Stroke="Black"/>
</Grid>
</Window>
绑定转换器:
public class DivideByConverter : IValueConverter
{
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The xmlentry to the language value</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int divider = 2;
if (value is double)
{
return (double)value / divider;
}
return value;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
这将采用 Binded 值 (ActualWidth) 并将其除以 2,ActualHeight 相同。因此,即使您的 from 已调整大小,该行也将保持在中心