通过使用附加属性机制,可以定义代表ActualHeight
和ActualWidth
的属性,并通过SizeChanged
事件进行更新。其用法如下所示。
<Grid local:SizeChange.IsEnabled="True" x:Name="grid1">...</Grid>
<TextBlock Text="{Binding ElementName=grid1,
Path=(local:SizeChange.ActualHeight)}"/>
以下是技术细节:
http://darutk-oboegaki.blogspot.com/2011/07/binding-actualheight-and-actualwidth.html
与其他解决方案相比,此解决方案的优点在于所定义的附加属性(SizeChange.ActualHeight 和 SizeChange.ActualWidth)可用于任何 FrameworkElement,而无需创建任何子类。 这个解决方案可重复使用且影响较小。
如果链接失效,请参考以下链接中的 SizeChange 类:
public class SizeChange : DependencyObject
{
#region Attached property "IsEnabled"
public const string IsEnabledPropertyName = "IsEnabled";
public static readonly DependencyProperty IsEnabledProperty
= DependencyProperty.RegisterAttached(
IsEnabledPropertyName,
typeof(bool),
typeof(SizeChange),
new PropertyMetadata(false, OnIsEnabledChanged));
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
#endregion
#region Attached property "ActualHeight"
public const string ActualHeightPropertyName = "ActualHeight";
public static readonly DependencyProperty ActualHeightProperty
= DependencyProperty.RegisterAttached(
ActualHeightPropertyName,
typeof(double),
typeof(SizeChange),
null);
public static double GetActualHeight(DependencyObject obj)
{
return (double)obj.GetValue(ActualHeightProperty);
}
public static void SetActualHeight(DependencyObject obj, double value)
{
obj.SetValue(ActualHeightProperty, value);
}
#endregion
#region Attached property "ActualWidth"
public const string ActualWidthPropertyName = "ActualWidth";
public static readonly DependencyProperty ActualWidthProperty
= DependencyProperty.RegisterAttached(
ActualWidthPropertyName,
typeof(double),
typeof(SizeChange),
null);
public static double GetActualWidth(DependencyObject obj)
{
return (double)obj.GetValue(ActualWidthProperty);
}
public static void SetActualWidth(DependencyObject obj, double value)
{
obj.SetValue(ActualWidthProperty, value);
}
#endregion
private static void OnIsEnabledChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var element = obj as FrameworkElement;
if (element == null)
{
return;
}
if (args.NewValue != null && (bool)args.NewValue == true)
{
Attach(element);
}
else
{
Detach(element);
}
}
private static void Attach(FrameworkElement element)
{
element.SizeChanged += HandleSizeChanged;
}
private static void Detach(FrameworkElement element)
{
element.SizeChanged -= HandleSizeChanged;
}
private static void HandleSizeChanged(object sender, SizeChangedEventArgs args)
{
var element = sender as FrameworkElement;
if (element == null)
{
return;
}
var width = args.NewSize.Width;
var height = args.NewSize.Height;
SetActualWidth(element, width);
SetActualHeight(element, height);
}
}