8,758
社区成员




/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
/// <summary>
/// y1绑定到grid的实际高度的一半
/// </summary>
public class Y1ToHeight : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double height = (double)value;
return height / 2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
/// <summary>
/// x2绑定到grid的实际宽度-5
/// </summary>
public class X2ToWidth : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value;
return width - 5;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在 XAML 中添加对程序集的引用(根据你实际项目名称而不同):
xmlns:local="clr-namespace:WpfApplication1"
添加资源:
<Window.Resources>
<local:Y1ToHeight x:Key="Y1ToHeight"/>
<local:X2ToWidth x:Key="X2ToWidth"/>
</Window.Resources>
最后绑定(主要看Y1和X2的绑定就可以,Grid的Name自己改):
<Grid x:Name="LayoutRoot">
<Line x:Name="line" X1="0" Y1="{Binding ElementName=LayoutRoot, Path=ActualHeight, Converter={StaticResource Y1ToHeight}}" X2="{Binding ElementName=LayoutRoot, Path=ActualWidth, Converter={StaticResource X2ToWidth}}" Y2="{Binding RelativeSource={RelativeSource Self}, Path=Y1}" StrokeThickness="4.0" Stroke="Blue"/>
</Grid>