Suspeso
Suspeso

Reputation: 15

WPF Sliders and switches control Array

I've got a significant amount of Sliders, Toggle Switches and Hide/Visible events going on in my window, handling the variables is easy using arrays until the point where I have to show them, then I had to declare tons of variable to make the conversion between booleans, doubles, and bytes.

Is there a way to place the controls into arrays?, let's say:

for (uint i = 1; i < 65; i++)
    Slider[i].Value = Parametros[i];

That would make my life so much easier.

Upvotes: 0

Views: 514

Answers (1)

Guttsy
Guttsy

Reputation: 2119

This crude example was somewhat hastily thrown together since the scope of your question is rather broad and unclear, but you want to make use of WPF's binding features and the ever-useful ItemsControl, e.g.

<ItemsControl ItemsSource="{Binding Sliders}">
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type SliderData}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding Name}" />
                <Slider Grid.Column="1" Value="{Binding Value}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Collection of sliders must be defined somewhere (the "data context"). If you want something easy, you can make your control your datacontext (i.e. DataContext = this in the window's constructor) but having a separate viewmodel (Google MVVM pattern examples for WPF) would be preferred.

public ObservableCollection<SliderData> Sliders { get; set; }

Something akin to your for loop to create the controls...

Sliders = new ObservableCollection<SliderData>();
Sliders.Add(new SliderData() { Name = "Slider 1", Value = 10 });
Sliders.Add(new SliderData() { Name = "Slider 2", Value = 7 });
...

C# supporting class

public class SliderData
{
    // Note: I'm doing this shorthand. You need INotifyPropertyChanged for bindings probably.
    public string Name { get; set; }
    public double Value { get; set; }
}

Upvotes: 1

Related Questions