tags:

views:

761

answers:

3

Here's the scenario

I have a Grid with some TextBlock controls, each in a separate cell in the grid. Logically I want to be able to set the Visibility on them bound to a property in my ViewModel. But since they're each in a separate cell in the grid, I have to set each TextBlock's Visibility property.

Is there a way of having a non-visual group on which I can set common properties of its children? Or am I dreaming?

A: 

I hope you have defined all of your cell UI elements inside a DataTemplate. You can do a small trick at the ViewModel level to achieve what you are looking for.

  1. Have Singletone class at the ViewModel which should have the Visibility or an equivalent property which you wanted to bind to every TextBlock.
  2. Singleton class should implement INotifypropertyChanged to get the change notification to the UI
  3. Bind the Singleton property in the XAML and control this property from anywhere in your application.

    < TextBlock Visibility="{Binding Source={x:Static local:Singleton.Instance},Path=Visibility}"

And a simple Singleton class can be implemented as

public class Singleton :INotifyPropertyChanged
{
    private Singleton() { }
    public static Singleton Instance
    {
        get
        {
            if (instance == null){ instance = new Singleton(); }
            return instance;
        }
    }
    private Visibility _visibility;
    public Visibility Visibility
    {
        get { return _visibility; }
        set 
        { 
            _visibility = value; 
            PropertyChanged( this, new PropertyChangedEventArgs("Visibility") );
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private static Singleton instance;
 }

Now you can control Singleton.Instance.Visibility = Visibility.Collapsed anywhere from your code behind

Jobi Joy
+1  A: 

There is no non-visual group that would make this possible.

Setting the Visibility properties, directly or in a common Style shared by all of the TextBlocks, is probably the simplest solution.

Ed Ball
A: 

Another option is to bind the visibility property of each item in your group of items to one single item, that way in your code behind you are only ever having to set the visibility of one item.