如何使用 将 childUserControl
的 Dependency Property绑定Style
到宿主元素的视图模型的属性?
我尝试了下面的代码,并且MyBlock.BlockIsOnlyOne
应该MyContainerViewModel.ViewModelIsOnlyOne
通过Style
's绑定到视图模型的属性 - Setter
。但由于某种原因,它不起作用—— MyBlock.BlockIsOnlyOne
' 值永远不会改变,尽管MyContainerViewModel.ViewModelIsOnlyOne
改变......
容器 XAML:
<UserControl x:Class="MyNs.MyContainer"
...
>
<UserControl.DataContext>
<vc:MyContainerViewModel x:Name="TheDataContext"/>
</UserControl.DataContext>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type vc:MyBlock}">
<Setter Property="BlockIsOnlyOne" Value="{Binding ViewModelIsOnlyOne}"/>
<!-- Tried this too, with no success: -->
<!-- <Setter Property="BlockIsOnlyOne" Value="{Binding ViewModelIsOnlyOne, ElementName=TheDataContext}"/> -->
</Style>
</Grid.Resources>
...
<vc:MyBlock DataContext="{Binding PortA[0]}" />
</Grid>
</UserControl>
容器的ViewModel
(只有重要的部分......):
[NotifyPropertyChangedAspect] // handles the INotifyPropertyChanged implementation...
class MyContainerViewModel{
...
public bool ViewModelIsOnlyOne { get; private set; }
...
}
MyBlock
UserControl
: _
class MyBlock : UserControl{
...
public static readonly DependencyProperty BlockIsOnlyOneProperty = DependencyProperty.Register(
"BlockIsOnlyOne", typeof (bool), typeof (MyBlock),
new PropertyMetadata(default(bool), BlockIsOnlyOne_PropertyChangedCallback));
private static void BlockIsOnlyOne_PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs a)
{
var @this = dependencyObject as MyBlock;
if (@this == null) return;
Trace.WriteLine(string.Format("Old: {0}, New: {1}", a.OldValue, a.NewValue)); // never seems to fire...
}
public bool BlockIsOnlyOne
{
get { return (bool) GetValue(BlockIsOnlyOneProperty); }
set { SetValue(BlockIsOnlyOneProperty, value); }
}
...
}