【发布时间】:2011-08-24 23:50:06
【问题描述】:
我的问题涉及 Silverlight(但我猜 WPF 也是如此)。
基本上我知道,如何在用户控件中创建依赖属性以及如何使其工作。但我想做但没有成功的是:在一个类中创建依赖属性(或多个),这个类将成为我的用户控件的依赖属性。
换句话说:
// my UserControl
public class DPTest : UserControl
{
// dependency property, which type is a class, and this class will be holding other dependency properties
public static readonly DependencyProperty GroupProperty =
DependencyProperty.Register("Group", typeof(DPGroup), typeof(DPTest), new PropertyMetadata(new DPGroup(), OnPropertyChanged));
public DPGroup Group
{
get { return (DPGroup)GetValue(GroupProperty); }
set { SetValue(GroupProperty, value); }
}
// this occurs only when property Group will change, but not when a member of property Group will change
static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DPTest g = d as DPTest;
// etc.
}
}
// a class, where I want to hold my dependency properties
public class DPGroup : DependencyObject
{
public static readonly DependencyProperty MyProperty1Property =
DependencyProperty.RegisterAttached("MyProperty1", typeof(int), typeof(DPGroup), new PropertyMetadata(1, OnPropertyChanged));
public int MyProperty1
{
get { return (int)GetValue(MyProperty1Property); }
set { SetValue(MyProperty1Property, value); }
}
// I would like to notify "the parent" (which means user control "DPTest" ), that member MyProperty1 has changed
static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DPTest g = d as DPTest;
if (g != null) g.textBox1.Text = g.Group.MyProperty1.ToString();
}
}
我想要实现的是通知(在 XAML 中的设计时)用户控件 DPTest,Group 属性 (Group.MyProperty1) 的成员更改了它的值。我设法让它在运行时发生,例如通过使用在DPGroup 类中定义的事件处理程序,但这在 xaml 的设计时不起作用。
<Grid x:Name="LayoutRoot" Background="White">
<local:DPTest>
<local:DPTest.Group>
<local:DPGroup MyProperty1="2"/>
</local:DPTest.Group>
</local:DPTest>
</Grid>
它在创建标签期间有效,但只是第一次:
<local:DPGroup MyProperty1="2"/>
在此之后,更改 MyProperty1 的值不会触发 DPTest.OnPropertyChange。可能会触发DBGroup.OnPropertyChanged,但这当然不会通知用户控件DPTest。 那么如何让DPTest 知道Group.MyProperty1 发生了变化?
我不想从MyProperty1 到在用户控件DPTest 内创建的各个属性进行任何绑定(不要复制属性),关键是在单独的类中有一组属性,所以我可以使用该组不止一次,例如:
// my UserControl
public class DPTest : UserControl
{
public DPGroup Group1 { ... }
public DPGroup Group2 { ... }
}
我看到了与 UIElement.RenderTransform 的类比(假设这是我的 Group 属性),例如 ScaleTransform
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RenderTransform>
<ScaleTransform ScaleX="0.4"/>
</Grid.RenderTransform>
</Grid>
ScaleX 类似于MyProperty1。 不同之处在于,ScaleX(在 XAML 中)的更改值将反映设计时的即时更改,而这正是我想要实现的。
我试图在整个 google/stack 溢出等中找到解决方案,但没有找到。 Everywhere 只是在用户控件中创建依赖属性的示例。
感谢您的宝贵时间。 非常感谢任何帮助。
编辑:根据 Harlow Burgess 的回答,a 设法在 Silverlight 中制作了一个工作示例。我将整个解决方案作为单独的答案放在下面。
【问题讨论】:
标签: c# wpf silverlight xaml dependency-properties