我有一种可怕的预感,我想做的事无法完成,但现在开始了。也许有更好的方法。
我在单独的文件中有一个 ResourceDictionary,被拉入 UserControl( View ):
<UserControl.Resources>
<ResourceDictionary Source="..\Resources.xaml"/>
</UserControl.Resources>
在 RD 中,我定义了一些按钮样式,其中一个包含条件,如果“IsCurrentFilter”转换器返回 True,则将前景设置为红色:
<Style x:Key="FilterButton" TargetType="Button" BasedOn="{StaticResource ButtonBase}">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Converter={StaticResource IsCurrentFilter}}" Value="True"/>
</MultiDataTrigger.Conditions>
<Setter Property="Foreground" Value="Red" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
转换器在同一个 RD 中定义,进一步向上:
<util:IsCurrentFilterConverter x:Key="IsCurrentFilter" ViewModel="{Binding}"/>
问题是转换器无法访问 View 模型(它需要它来进行比较),并且 ViewModel 属性只是拒绝绑定(bind)到任何东西。错误是...
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'IsCurrentFilterConverter' (HashCode=50804710); target property is 'ViewModel' (type 'Object')
...这有点道理,据我所知,它不在可视化树中。
那么,我怎样才能绑定(bind)到这个 ResourceDictionary 中的 View 模型?
请您参考如下方法:
你做错了。转换器不应以这种方式绑定(bind)到 View 模型。它应该完全取决于它的输入值。以 View 模型是按钮的数据上下文或在逻辑树上的可预测位置可用的方式设置按钮。然后您的绑定(bind)转换器可以将 View 模型“转换”为 bool 值。更好的是,添加一个提供所需 bool 值的 viewmodel 属性并绑定(bind)到它。
