Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How do you add visibility properties to usercontrol in WPF

Posted on 2015-02-24
5
Medium Priority
?
2,249 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

636 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