我相信這是一個使用DependencyProperty的Value繼承權的例子。
基本上,childcontrol將直接繼承父控制SensorRotationAngle值的值。
public class ParentControlGrid : Grid
{
// Dependency Property
public static readonly DependencyProperty SensorRotationAngleProperty =
DependencyProperty.Register("SensorRotationAngle", typeof(int),
typeof(ParentControlGrid), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
// .NET Property wrapper
public int SensorRotationAngle
{
get { return (int)GetValue(SensorRotationAngleProperty); }
set { SetValue(SensorRotationAngleProperty, value); }
}
}
public class ChildControlTextBox : TextBox
{
// Dependency Property
public static readonly DependencyProperty SensorRotationAngleProperty;
static ChildControlTextBox()
{
SensorRotationAngleProperty = ParentControlGrid.SensorRotationAngleProperty.AddOwner(typeof(ChildControlTextBox),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
}
// .NET Property wrapper
public int SensorRotationAngle
{
get { return (int)GetValue(SensorRotationAngleProperty); }
set { SetValue(SensorRotationAngleProperty, value); }
}
}
<Window x:Class="WpfTestProj.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfTestProj="clr-namespace:WpfTestProj"
Title="MainWindow" Height="350" Width="525">
<wpfTestProj:ParentControlGrid SensorRotationAngle="500">
<wpfTestProj:ChildControlTextBox Text="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=SensorRotationAngle}" />
</wpfTestProj:ParentControlGrid>
非常感謝隊友,它的工作就像一個魅力! –
不客氣:-) – Martin