开发者

Make checkboxes from a int value in C# (for silverlight)

I want to read a parsed int 开发者_开发知识库value from silverlight slider to make checkboxes.

For example the slider has value 7, I`ll press a button and make 7 checkboxes.

How do I do that?


If you need to capture their values in a viewmodel, adding the checkboxes in the code-behind may not be the best approach.

class MainWindowViewModel : INotifyPropertyChanged
{
    private int _sliderValue;
    public int SliderValue
    {
        get
        {
            return _sliderValue;
        }
        set
        {
            _sliderValue = value;

            while ( SliderValue > CheckboxValues.Count )
            {
                CheckboxValues.Add( false );
            }

            // remove bools from the CheckboxValues while SliderValue < CheckboxValues.Count
            // ...
        }
    }


    private ObservableCollection<Boolean> _checkboxValues = new ObservableCollection<Boolean>();
    public ObservableCollection<Boolean> CheckboxValues
    {
        get
        {
            return _checkboxValues;
        }
        set
        {
            if ( _checkboxValues != value )
            {
                _checkboxValues = value;
                RaisePropertyChanged( "CheckboxValues" );
            }
        }
    }

then in xaml, something like:

 <ItemsControl ItemsSource="{Binding CheckboxValues}">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type sys:Boolean}">
                <CheckBox IsChecked="{Binding self}">Hello World</CheckBox>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>


Here is a working example. It even remembers the checked state of boxes when more are added.

Assuming this XAML:

<Slider Minimum="0" Maximum="7" SmallChange="1" LargeChange="1"
        x:Name="mySlider" ValueChanged="mySlider_ValueChanged" />

<StackPanel x:Name="chkContainer" />

This is the event handler

private void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    if (chkContainer != null) // It could be null during page creation (add event handler after construction to avoid this)
    {
        // The following works because the both the small and large change are one
        // If they were larger you may have to add (or remove) more at a time
        if (chkContainer.Children.Count() < mySlider.Value)
        {
            chkContainer.Children.Add(new CheckBox { Content = mySlider.Value.ToString() });
        }
        else
        {
            chkContainer.Children.RemoveAt(int.Parse(mySlider.Value.ToString()));
        }
    }
}


A checkbox can be instantiated and added to a default project page with the following code.

        var cb = new CheckBox();
        ContentPanel.Children.Add(cb);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜