在定义WPF样式时,我经常使用Expression Blend <d:Style.DataContext>
标签使Intellisense知道运行时DataContext是什么。效果很好。不幸的是,我似乎无法在资源词典中完成这项工作,并且不清楚原因。
例如,在这里以RadTabItem
的样式,我告诉Intellisense SettingsPageVm
将是DataContext:
<UserControl x:Class="Views.ConfigureView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:tk="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:viewModels="clr-namespace:ViewModels"
d:DataContext="{d:DesignInstance viewModels:ConfigureVm}">
<Grid>
<tk:RadTabControl ItemsSource="{Binding Categories}" >
<tk:RadTabControl.Resources>
<!-- Tell setters that SettingsPageVm will be the datacontext -->
<Style TargetType="{x:Type tk:RadTabItem}">
<d:Style.DataContext>
<x:Type Type="viewModels:SettingsPageVm" />
</d:Style.DataContext>
<!-- (Imagine many setters here, binding to SettingsPageVm) -->
这很好。
但是,如果尝试将相同的样式移至单独的ResourceDictionary,则Visual Studio会抱怨。编辑器在d:Style.DataContext
声明下方波浪形地放置一个蓝色,并将其突出显示为红色。编译器抱怨如下:
1> I:\ Dev \ MyApp \ Resources \ Styles \ DialogStyles.xaml(13,14):错误 MC4004:样式不能包含子项“ TypeExtension”。风格孩子必须 是Setter,因为它已添加到Setters集合中。 13号线 位置14。
为什么这在一种情况下有效而在另一种情况下无效?
<ResourceDictionary 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"
xmlns:viewModels="clr-namespace:ViewModels"
xmlns:tk="http://schemas.telerik.com/2008/xaml/presentation"
>
<Style x:Key="SettingsPageTabStyle" TargetType="{x:Type tk:RadTabItem}">
<d:Style.DataContext> <!-- *** ERROR *** -->
<x:Type Type="viewModels:SettingsPageVm" />
</d:Style.DataContext>
</Style>
</ResourceDictionary>
答案 0 :(得分:0)
回答我自己的问题,因为半天后我偶然发现了这个问题。
我忽略添加
mc:Ignorable="d"
行到我的XAML。一旦我做到了,一切都会很好。
(这只是我确定已经学过的那些晦涩的WPF课程之一,然后在过去几年中从事WPF的工作至少至少一次(也许两次)被忘记了。)