我有按钮自定义视图:
<UserControl>
...
<Rectangle x:Name="Highlight" Style="{DynamicResource HighlightStyle}"/>
...
<DataTrigger Binding="{Binding Path=IsHighlighted}" Value="true">
<Setter TargetName="Highlight" Property="Opacity" Value="1"/>
</DataTrigger>
...
</UserControl>
Run Code Online (Sandbox Code Playgroud)
并且在父视图中使用按钮,如下所示:
<local:MyButton x:Name="Btn1" DataContext="{Binding Path=Btn1}" />
Run Code Online (Sandbox Code Playgroud)
因此,当我需要突出显示按钮时,我正在通过代码执行此操作.喜欢Btn1.IsHighlighted=true;
但在某些时候我需要直接从父XAML设置它.可能吗?
即在一些特定的观点我不想Btn1.IsHighlighted被使用.相反,我想要这样的东西:
<local:MyButton x:Name="Btn1" DataContext="{Binding Path=Btn1}" IsHighlighted="true" />
Run Code Online (Sandbox Code Playgroud)
您可以将IsHighlighted注册为MyButton类的属性
private static readonly DependencyProperty IsHighlightedProperty = DependencyProperty.Register
(
"IsHighlighted",
typeof(bool),
typeof(MyButton),
new PropertyMetadata((bool)false)
);
public bool IsHighlighted
{
get { return (bool) GetValue(IsHighlightedProperty); }
set { SetValue(IsHighlightedProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)
编辑添加XAML使用
你的MyButton XAML应该有这样的东西
<Rectangle x:Name="Highlight" Width="100">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Style.Triggers>
<DataTrigger Binding="{Binding IsHighlighted}" Value="True">
<Setter Property="Opacity" Value="1" />
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
Run Code Online (Sandbox Code Playgroud)
我实际上在这里测试了Property ="Fill"和Value ="Green".但改为符合你的情况.
父视图应该有
<local:MyButton x:Name="Btn1" DataContext="{Binding Path=Btn1}" IsHighlighted="true" />
Run Code Online (Sandbox Code Playgroud)