Solved

How do you add visibility properties to usercontrol in WPF

Posted on 2015-02-24
5
1,470 Views
Last Modified: 2015-02-25
I have a user control that I have added a  grid to that acts as a badge to display a number.  See below:
UserControl
I want to add a property that gives me the ability to set the visibility of the grid that contains the circle.  I have tried looking at dependency properties, but nothing seems to work.  I want to add a property so that in xaml I can add something like 'badgeVisibility="Hidden"'   Or 'badgeVisibility="Visible"'

Here is the code for my usercontrol:

<UserControl x:Class="colorCompButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Height="179" Width="317">
    <UserControl.Resources>
        
    </UserControl.Resources>
 
    <Grid>
        <Rectangle x:Name="rect"  Fill="Coral" HorizontalAlignment="Left" Height="147"  VerticalAlignment="Top" Width="286" x:FieldModifier="public"/>
        <Image x:Name="image" Height="110" Margin="10,10,10,0" VerticalAlignment="Top" x:FieldModifier="public"/>
 
 
        <TextBlock x:Name="textBlock" Margin="0,111,10,2" Text="TEST" Background="Transparent" Foreground="White" FontSize="20" Padding="3"/>
        <Grid Margin="237,97,0,0" x:Name="countBadge" Height="88" VerticalAlignment="Top" HorizontalAlignment="Left" Width="94">
            <Border BorderBrush="Maroon" BorderThickness="1" CornerRadius="120" Background="#FF4B1076" HorizontalAlignment="Left" Height="76"  VerticalAlignment="Top" Width="76"></Border>
            <Border BorderBrush="black" Margin="2,2,0,0" BorderThickness="3" Opacity=".5" CornerRadius="120"  HorizontalAlignment="Left" Height="74"  VerticalAlignment="Top" Width="74"></Border>
            <Border BorderBrush="White" BorderThickness="3" CornerRadius="120"  HorizontalAlignment="Left" Height="78" VerticalAlignment="Top" Width="78">
                <Label x:Name="resCount" Content="46" FontSize="25"  Foreground="White"  HorizontalContentAlignment="center" VerticalContentAlignment="center"/>
            </Border>
        </Grid>
    </Grid>
</UserControl>

Open in new window


Thanks for any help you can give me on this.
0
Comment
Question by:G Scott
  • 2
  • 2
5 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40630759
You would need to add a dependency property, as described here:

A SIMPLE PATTERN FOR CREATING RE-USEABLE USERCONTROLS IN WPF / SILVERLIGHT
http://www.scottlogic.com/blog/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html

public partial class FieldUserControl : UserControl
{
  #region Label DP

  /// <summary>
  /// Gets or sets the Label which is displayed next to the field
  /// </summary>
  public String Label
  {
    get { return (String)GetValue(LabelProperty); }
    set { SetValue(LabelProperty, value); }
  }

  /// <summary>
  /// Identified the Label dependency property
  /// </summary>
  public static readonly DependencyProperty LabelProperty =
      DependencyProperty.Register("Label", typeof(string),
        typeof(FieldUserControl), new PropertyMetadata(""));

  #endregion

  public FieldUserControl()
  {
    InitializeComponent();
  }
}

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40630761
VB.NET:

Public Partial Class FieldUserControl
	Inherits UserControl
	#Region "Label DP"

	''' <summary>
	''' Gets or sets the Label which is displayed next to the field
	''' </summary>
	Public Property Label() As [String]
		Get
			Return DirectCast(GetValue(LabelProperty), [String])
		End Get
		Set
			SetValue(LabelProperty, value)
		End Set
	End Property

	''' <summary>
	''' Identified the Label dependency property
	''' </summary>
	Public Shared ReadOnly LabelProperty As DependencyProperty = DependencyProperty.Register("Label", GetType(String), GetType(FieldUserControl), New PropertyMetadata(""))

	#End Region

	Public Sub New()
		InitializeComponent()
	End Sub
End Class

Open in new window

0
 
LVL 22

Accepted Solution

by:
ambience earned 500 total points
ID: 40630929
This should do

	public partial class MyControl : UserControl
	{
		public MyControl()
		{
			InitializeComponent();
		}

		public static readonly DependencyProperty BadgeVisibileProperty =
			DependencyProperty.Register("BadgeVisibile", typeof(Visibility), typeof(MyControl), new PropertyMetadata(Visibility.Visible));

		public Visibility BadgeVisibile
		{
			get { return (Visibility)GetValue(BadgeVisibileProperty); }
			set { SetValue(BadgeVisibileProperty, value); }
		}
	}

Open in new window


and the XAML

<UserControl x:Class="Learning.Desktop.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:Local="clr-namespace:MySampleApp.Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
	<Grid>
		<Button Content="Button" VerticalAlignment="Top" 
				Visibility="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=BadgeVisibile}"/>
	</Grid>
</UserControl>

Open in new window


The important piece here is the Binding of Visibility to the BadgeVisible property on the UserControl and not the DataContext, and therefore the use of RelativeSource. In simple words it means, find the parent of type "UserControl" and bind to its "BadgeVisibile" property. NOTE: you can also use a more strict type here like say

{x:Type Local:MyUserControl}

(you'll have to add the xmlns alias Local)
0
 
LVL 1

Author Closing Comment

by:G Scott
ID: 40630971
Thanks, ambience.  It was not working until I read the part about adding the Local alias.
0
 
LVL 22

Expert Comment

by:ambience
ID: 40630990
The posted code and XAML, as is, works for me. It shouldn't need a more specific type to find the parent UserControl
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now