【发布时间】:2011-08-10 12:18:13
【问题描述】:
假设我们有一个只有一个状态变量的简单 UI。此状态表示为枚举值,例如。 Phase1、Phase2 等。根据 UI 所处的状态(阶段)、不同的 UI 元素、应该可见或隐藏的窗口。
代码如下:
public enum Phases { Phase1, Phase2, Phase3 }
public class UIStateModel : DependencyObject
{
public static DependencyProperty CurrentStateProperty =
DependencyProperty.Register("CurrentStateProperty",
typeof(Phases),
typeof(UIStateModel));
public Phases CurrentState
{
get { return (Phases)GetValue(CurrentStateProperty); }
set { SetValue(CurrentStateProperty, value); }
}
public Visibility Window1Visible // Databound to Window1.Visibility
{
get
{
if (this.CurrentState == Phases.Phase1) return Visibility.Visible;
else return Visibility.Hidden;
}
}
public Visibility Window2Visible // Databound to Window2.Visibility
{
get
{
if (this.CurrentState == Phases.Phase2) return Visibility.Visible;
else return Visibility.Hidden;
}
}
...
}
问题是与上面代码的数据绑定不起作用,因为WindowXVisible属性不是DependencyProperty-s。如果我将所有属性都转为 DependencyProperty,那么我将在状态管理中引入冗余。除了保持一切同步的额外负担外,它甚至会变得不一致(如果我不能很好地同步)。
什么是避免在 UI 状态管理中引入冗余但仍利用 DependencyProperty-s 促进的数据绑定功能的正确方法?
【问题讨论】:
-
只是想知道为什么您没有扩展
ItemsControl的 DependencyProperty,当它改变时会改变您孩子的可见性?我还发布了另一种方法作为答案。
标签: .net wpf dependency-properties redundancy