2011-01-14 17 views
0

我想從Silverlight滑塊讀取經過分析的int值以創建複選框。使用C#中的int值創建複選框

例如滑塊的值爲7,我將按下一個按鈕並設置7個複選框。

我該怎麼做?

+0

請注意了Windows Phone 7是基於Silverlight 3中(不4)。我相應地更新了您的問題(和標籤)。 – 2011-01-14 09:45:32

回答

0

這是一個工作示例。它甚至可以在添加更多內容時記住已檢查的框的狀態。

假設這XAML:

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

<StackPanel x:Name="chkContainer" /> 

這是事件處理程序

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())); 
     } 
    } 
} 
+0

馬特規則..:p – 2011-04-12 22:37:53

0

可以使用以下代碼實例化複選框並將其添加到默認項目頁面。

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

如果您需要捕獲它們的值在視圖模型,將複選框中的代碼隱藏可能不最好的方法。

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"); 
      } 
     } 
    } 

然後在XAML中,是這樣的:

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