【发布时间】:2011-10-16 09:54:43
【问题描述】:
当我将一个属性声明为普通依赖属性时,它会起作用,但是当它被声明为附加时,它不会。我不确定,我在这里错过了什么。请帮忙。以下是代码。
(带有依赖属性的第 1 组效果很好,但带有附加依赖属性的第 2 组效果不佳)
<StackPanel Name="PanelControl" Orientation="{Binding ElementName=MainWindow, Path=ControlOrientation, Converter={StaticResource ResourceKey=LocalConvertor}}"/>
设置 1
FrameworkPropertyMetadata metaData1 = new FrameworkPropertyMetadata(Orientation.Vertical, FrameworkPropertyMetadataOptions.AffectsRender);
ControlOrientationProperty = DependencyProperty.RegisterAttached("ControlOrientation", typeof(Orientation), typeof(CustomTextBoxUsingDependencyProperty), metaData1);
public Orientation ControlOrientation
{
get { return (Orientation)(GetValue(ControlOrientationProperty)); }
set { SetValue(ControlOrientationProperty, value); }
}
<clist:CustomTextBoxUsingDependencyProperty Width="742" Height="100" ControlOrientation="Horizontal"/>
第二组
ControlOrientationProperty = DependencyProperty.RegisterAttached("ControlOrientation", typeof(Orientation), typeof(CustomTextBoxUsingDependencyProperty), metaData1);
public static void SetControlOrientation(UIElement element, Orientation value)
{
element.SetValue(CustomTextBoxUsingDependencyProperty.ControlOrientationProperty, value);
}
public static Orientation GetControlOrientation(UIElement element)
{
return (Orientation)element.GetValue(CustomTextBoxUsingDependencyProperty.ControlOrientationProperty);
}
<clist:CustomTextBoxUsingDependencyProperty Width="742" Height="100">
<Button Content="Test" clist:CustomTextBoxUsingDependencyProperty.ControlOrientation="Horizontal"/>
</clist:CustomTextBoxUsingDependencyProperty>
【问题讨论】:
-
“正确”是什么意思?您可以使用属性更改回调并根据需要处理属性值。
-
我的意思是,案例 2 没有更新 StackPanel 的方向,但是当我将属性更改事件附加到附加属性时;我可以看到新的价值即将到来。现在,这只是一次绑定,在情况 1 中,也没有附加属性更改的事件处理程序。那么为什么案例 1 有效而案例 2 无效?我想不通!
-
StackPanel 绑定到 MainWindow,而属性用于自定义控件和按钮。
标签: wpf wpf-controls attached-properties