標簽:sel ane readonly enter bin inherits new aml 代碼
?依赖属性的传递,在XAML逻辑树上, 内部的XAML元素,关联了外围XAML元素同名依赖属性值 ;
<Window x:Class="Custom_DPInherited.DPInherited"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
FontSize="18"
Title="依赖属性的继承">
<StackPanel >
<Label Content="继承自Window的FontSize" />
<Label Content="显式设置FontSize"
TextElement.FontSize="36"/>
<StatusBar>Statusbar没有继承自Window的FontSize</StatusBar>
</StackPanel>
</Window>
?在上面XAML代碼中。Window.FontSize设置会影响所有内部子元素字体大小,这就是依赖属性的值传递。如第一个Label没有定义FontSize,所以它继承了Window.FontSize值。但一旦子元素提供了显式设置,这种继承就会被打断,所以Window.FontSize值对于第二个Label不再起作用。
?但是,並不是所有元素都支持屬性值繼承的,如StatusBar、Tooptip和Menu控件。另外,StatusBar等控件截獲了從父元素繼承來的屬性,使得該屬性也不會影響StatusBar控件的子元素。例如,如果我們在StatusBar中添加一個Button。那麽這個Button的FontSize屬性也不會發生改變,其值爲默認值
獲取外圍依賴屬性值
定义自定义依赖属性时,可通过AddOwer方法可以使依赖属性,使用外围元素的依赖属性值。具体的实现代碼如下所示
public class CustomStackPanel : StackPanel
{
public static readonly DependencyProperty MinDateProperty;
static CustomStackPanel()
{
MinDateProperty = DependencyProperty.Register("MinDate", typeof(DateTime), typeof(CustomStackPanel), new FrameworkPropertyMetadata(DateTime.MinValue, FrameworkPropertyMetadataOptions.Inherits));
}
public DateTime MinDate
{
get { return (DateTime)GetValue(MinDateProperty); }
set { SetValue(MinDateProperty, value); }
}
}
public class CustomButton :Button
{
private static readonly DependencyProperty MinDateProperty;
static CustomButton()
{
// AddOwner方法指定依赖属性的所有者,从而实现依赖属性的传递,即CustomStackPanel的MinDate属性可以传递给CustomButton控件。
// 注意FrameworkPropertyMetadataOptions的值为Inherits
MinDateProperty = CustomStackPanel.MinDateProperty.AddOwner(typeof(CustomButton), new FrameworkPropertyMetadata(DateTime.MinValue, FrameworkPropertyMetadataOptions.Inherits));
}
public DateTime MinDate
{
get { return (DateTime)GetValue(MinDateProperty); }
set { SetValue(MinDateProperty, value); }
}
}
<Window x:Class="Custom_DPInherited.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Custom_DPInherited"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="实现自定义依赖属性的值传递" Height="350" Width="525">
<Grid>
<local:CustomStackPanel x:Name="customStackPanle" MinDate="{x:Static sys:DateTime.Now}">
<!--CustomStackPanel的依赖属性-->
<ContentPresenter Content="{Binding Path=MinDate, ElementName=customStackPanle}"/>
<local:CustomButton Content="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=MinDate}" Height="25"/>
</local:CustomStackPanel>
</Grid>
</Window>
標簽:sel ane readonly enter bin inherits new aml 代碼
原文地址:https://www.cnblogs.com/MonoHZ/p/14944142.html