跟进Jobi Joy 的回答
您不能OneWayToSource
在 Xaml 中为 ReadOnly 依赖属性 ActualHeight 执行直接绑定,但有许多解决方法。Kent Boogaart在这个问题上的回答是我最喜欢的。所做的是它使用一个附加行为来侦听SizeChanged
任何事件FrameworkElement
并相应地更新两个附加属性,宽度和高度。
TextBlock
例如,ActualHeight
可以用来推入 ViewModel 的 Height 属性,例如
<TextBlock local:ActualSizeBehavior.ObserveActualSize="True"
local:ActualSizeBehavior.ActualHeight="{Binding Path=Height,
Mode=OneWayToSource}"
.../>
同步两个 ScrollViewers
您可以使用 aDependencyPropertyDescriptor
来监听属性的变化,VerticalOffsetProperty
或者订阅ScrollChanged
事件并调用ScrollToVerticalOffset
。例子
Xaml
<ScrollViewer Name="scrollViewerLeft"
ScrollChanged="scrollViewerLeft_ScrollChanged">
<ScrollViewer Name="scrollViewerRight"
ScrollChanged="scrollViewerRight_ScrollChanged">
事件处理程序背后的代码
private void scrollViewerLeft_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
scrollViewerRight.ScrollToVerticalOffset(scrollViewerLeft.VerticalOffset);
}
private void scrollViewerRight_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
scrollViewerLeft.ScrollToVerticalOffset(scrollViewerRight.VerticalOffset);
}
实际尺寸行为
public static class ActualSizeBehavior
{
public static readonly DependencyProperty ActualSizeProperty =
DependencyProperty.RegisterAttached("ActualSize",
typeof(bool),
typeof(ActualSizeBehavior),
new UIPropertyMetadata(false, OnActualSizeChanged));
public static bool GetActualSize(DependencyObject obj)
{
return (bool)obj.GetValue(ActualSizeProperty);
}
public static void SetActualSize(DependencyObject obj, bool value)
{
obj.SetValue(ActualSizeProperty, value);
}
private static void OnActualSizeChanged(DependencyObject dpo,
DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = dpo as FrameworkElement;
if ((bool)e.NewValue == true)
{
element.SizeChanged += element_SizeChanged;
}
else
{
element.SizeChanged -= element_SizeChanged;
}
}
static void element_SizeChanged(object sender, SizeChangedEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
SetActualWidth(element, element.ActualWidth);
SetActualHeight(element, element.ActualHeight);
}
private static readonly DependencyProperty ActualWidthProperty =
DependencyProperty.RegisterAttached("ActualWidth", typeof(double), typeof(ActualSizeBehavior));
public static void SetActualWidth(DependencyObject element, double value)
{
element.SetValue(ActualWidthProperty, value);
}
public static double GetActualWidth(DependencyObject element)
{
return (double)element.GetValue(ActualWidthProperty);
}
private static readonly DependencyProperty ActualHeightProperty =
DependencyProperty.RegisterAttached("ActualHeight", typeof(double), typeof(ActualSizeBehavior));
public static void SetActualHeight(DependencyObject element, double value)
{
element.SetValue(ActualHeightProperty, value);
}
public static double GetActualHeight(DependencyObject element)
{
return (double)element.GetValue(ActualHeightProperty);
}
}