WPF 使用 DependencyProperty 更改 UserControl 中标签的背景
我有一个非常简单的用户控件,如下所示。我试图在控件中的属性发生更改时更改 Label 元素的背景,但它不起作用:当我更改控件实例上的 Selected 属性时,标签的背景颜色不会更改。
谢谢!
背后代码:
public static readonly DependencyProperty SelectedProperty =
DependencyProperty.Register("Selected",
typeof(bool),
typeof(UICatcherContactlistItem),
new FrameworkPropertyMetadata((bool)false));
public bool Selected
{
get { return (bool)GetValue(SelectedProperty); }
set { SetValue(SelectedProperty, value); }
}
Xaml:
<UserControl x:Class="UICatcherContactlistItem" [....]>
<Label Name="name" Foreground="#888888">
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding Selected}" Value="True">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding Selected}" Value="False">
<Setter Property="Background" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label>
</UserControl>
I have a very simple UserControl as shown below. I'm trying to get the background of the Label element to change whenever a property in the control changes, but it's not working: when I change the Selected property on the control instance, the label's background color does not change.
Thanks!
Code behind:
public static readonly DependencyProperty SelectedProperty =
DependencyProperty.Register("Selected",
typeof(bool),
typeof(UICatcherContactlistItem),
new FrameworkPropertyMetadata((bool)false));
public bool Selected
{
get { return (bool)GetValue(SelectedProperty); }
set { SetValue(SelectedProperty, value); }
}
Xaml:
<UserControl x:Class="UICatcherContactlistItem" [....]>
<Label Name="name" Foreground="#888888">
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding Selected}" Value="True">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding Selected}" Value="False">
<Setter Property="Background" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label>
</UserControl>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需给出 UserControl 名称即可执行此代码,此处我使用 test。
如果您在用户控件上使用 Dependency 属性,则可以通过 ElementName 属性访问该属性,或者必须为元素设置 Datacontext,如 name.DataContext=this..
just give the UserControl name to execute this code, here iam using test.
If you are using Dependency property on the usercontrol you can access the property by either ElementName property or you have to set the Datacontext for the element like name.DataContext=this..