wonea
wonea

Reputation: 4969

Accessing and changing WPF elements through a variable name

I've got a series of buttons labelled for the 24 hour clock. For example;

<StackPanel Orientation="Horizontal">
     <ToggleButton Content="00:00" Name="thetime0000"/>
     <ToggleButton Content="01:00" Name="thetime0100" />
     <ToggleButton Content="02:00" Name="thetime0200" />
     <ToggleButton Content="03:00" Name="thetime0300" />

etc.

Now I store the values of each element in a database as a BIT, and I'm trying to associate them so they are selected or not. I had an idea of trying to enumerate all the toggle buttons but can't get that far;

System.Windows.Controls.Primitives.ToggleButton [24] fudge = 
   new System.Windows.Controls.Primitives.ToggleButton [24];
   fudge[0] = thetime0000;
   fudge[1] = thetime0100;

Could I call the element directly by element name or number? Any ideas?

Upvotes: 0

Views: 332

Answers (2)

Amsakanna
Amsakanna

Reputation: 12934

Create the following:

A Horizontal ListView:

<ListView ItemsSource="{Binding myClocks}"> 
    <ListView.ItemsPanel>  
        <ItemsPanelTemplate>  
            <VirtualizingStackPanel Orientation="Horizontal" />  
        </ItemsPanelTemplate>  
    </ListView.ItemsPanel>  
    <ListView.ItemTemplate>
        <DataTemplate>
            <ToggleButton />
        </DataTemplate>
    </ListView.ItemTemplate>      
</ListView> 

A class containing two members Time and IsChecked:

Class MyClock : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    string time;
    Nullable<bool> isChecked;
    public string Time 
    { 
        get { return time }; 
        set
        {
            time = value;
            OnPropertyChanged("Time");
        }
    };
    // Similarly create property for isChecked        
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    } 
}

For more details on implementing property change notification see here

An ObservableCollection containing a list of MyClock instances:

ObservableCollection<MyClock> myClocks = new ObservableCollection<MyClock>();

Add the 24 items to the collection:

for(int i=0; i<24; i++)
    myClocks.Add(new MyClock{ Time = String.Format("00:{0}",i.ToString("D2"}), IsChecked = false });

Your ListView's ItemsSource is already set to the ObservableCollection in the markup(see above)

Hope you've already set the DataContext.

Now whenever the user clicks the ToggleButton, the value True/False/Null will be propagated to your property and vice versa.

Upvotes: 0

PMN
PMN

Reputation: 1731

You can access the controls by name:

thetime0000.IsChecked = true;

Upvotes: 1

Related Questions