Solved

How do you add visibility properties to usercontrol in WPF

Posted on 2015-02-24
5
1,670 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Javascript to set controls visibility 5 38
Help with preventing downloading a zip file 10 37
Winform Module - What is the ASP.Net equiv 2 23
vb.net class 3 17
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

832 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