假设我想显示一个日历,每一天(DayViewModel
)都可以有这样的属性,这些属性会影响样式:
- 是当前月份的日期
- 是周末
- 可用天数
在此基础上,我想将我的DayContentView
设置为如下样式:
- 如果当前月份的日期-〉不透明度1
- 如果不是当前月份-〉不透明度0.5
- 如果周末-〉背景颜色为红色
- 如果可用-〉背景颜色为绿色
此外,最后一个属性(“当天可用”)可以根据用户的操作(单击按钮“检查可用性”)进行更改。
在其他框架中,我会创建一些样式/样式类,并根据这些标志相应地分配它们。但由于StyleClass
是不可绑定的,我不能。我可以吗?也许有一些变通办法。
另一个选择是为所有的组合创建一个单独的样式(如果需要的话,使用继承)。但是首先,组合的数量增加到2^n,第二个问题是,我不知道如何为一个更改名称的视图动态地更改整个样式。这可能吗?
结束我的长问题:我不想在视图模型中存储颜色、字体大小、不透明度等值,然后手动绑定所有值。
2条答案
按热度按时间wvt8vs2t1#
使用
DataTrigger
可以实现同样的效果。结果:
MainPage.xaml
DayModel.cs
MainViewModel.cs
**EDIT:**多个控件共享样式
以下是多个控件(在此范例中为三个
TextBlock
中的两个)如何共用具有Triggers
的相同Style
:结果如下所示:
zed5wv102#
我本打算按照@ToolmakerStave的建议添加一个示例,但同时我发现了一个似乎很不错的解决方案,所以我决定将其分享给大家。
1.声明实现
INotifyPropertyChanged
的视图模型1.创建XAML文件并在其中定义所有样式
1.在我的例子中,在代码背后检测绑定上下文(视图模型)的变化及其所有动态变化的属性(
IsAvailable
1.检测到更改后,使用XAML文件中定义的样式创建样式,并按所需顺序应用这些样式(进行更新)
1.将最终样式指定给特定元素
所以从我的观点模型开始:
假设只有
IsAvailable
属性可以在某个用户操作后更改。然后,我有一个XAML视图,它定义了所有需要的样式,但它们并没有直接在这个文件中使用。我将在后面的代码中使用它们。所有需要设置样式的元素都设置了
x:Name
属性,以便从代码中获得对它们的引用:现在有一个helper类,允许用另一个样式更新一个样式:
最后一部分,后面的代码:
最后一个想法在最后的代码之后:)如果没有更简单的解决方案,那么能够在XAML中这样做就很好了(伪代码):
然后根据定义的条件,按照定义的顺序依次应用创建所有样式。