Reputation: 41530
I have a label in a WPF user control:
<Label Name="lblTitle"></Label>
In the code behind, I define a dependency property called Customer
. Customer itself has a property called IsNew
. I would like to bind lblTitle.Content
so that when IsNew == true
then it would be "Create New", and when it is false
then the Content
would be set to "Update" (I would do this in ASP.net by setting lblTitle.Text = IsNew ? "Create New" : "Update";
).
What is the best way to do this?
Edit
Here is my declaration of the property in the code behind:
public Cust Customer{
get { return (Cust)GetValue(CustomerProperty); }
set { SetValue(CustomerProperty, value); }
}
public static readonly DependencyProperty CustomerProperty =
DependencyProperty.Register("Customer", typeof(Cust), typeof(Name_Of_Control), new UIPropertyMetadata(new Cust()));
Upvotes: 3
Views: 4015
Reputation: 5015
This should help you
<Label Name="lblTitle">
<Label.Style>
<Style TargetType="{x:Type Label}">
<Setter Property="Label.Content" Value="Update" />
<Style.Triggers>
<DataTrigger Binding="{Binding Customer.IsNew}" Value="True">
<Setter Property="Label.Content" Value="Create New" />
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
Also, if you want to apply a style from your resources, you can use BasedOn
attribute:
<Style BasedOn="{StaticResource MyLabelStyleName}" TargetType="{x:Type Label}">
With that you'll be able to set a new content value based on Customer.IsNew
property as well as a style for your Label
control.
Upvotes: 4
Reputation: 12356
Try this.
<Label Name="lblTitle">
<Label.Style TargetType="Label">
<Setter Property="Content" Value="Update" />
<Style.Triggers>
<DataTrigger Binding="{Binding Customer.IsNew}" Value="True">
<Setter Property="Content" Value="Create New" />
</DataTrigger>
</Style.Triggers>
</Label.Style>
</Label>
Upvotes: 0
Reputation: 52
One other thing worth noting is that if your label is simply displaying text then you are better of using a TextBlock rather than a label:
http://joshsmithonwpf.wordpress.com/2007/07/04/differences-between-label-and-textblock/
Upvotes: -3