Luk*_*uke 2 c# data-binding silverlight binding
我有X个RadioButtons(Silverlight).通常这个值在2-5之间.称之为"开关".每个单选按钮都绑定到该类的属性.
示例属性看起来像
private bool _radio1;
public bool Radio1{
set{
_radio1 = value;
_radioX = !value; // make all others false
}
get{ return _radio1 }
}
Run Code Online (Sandbox Code Playgroud)
基本思想是,如果选择一个无线电,则关闭所有其他无线电.
我尝试过使用其他方法,与使用模板创建列表相比,这个方法似乎最简单(特别是在某些情况下我有其他按钮涉及无线电)
目前我有两个要求,我需要一个具有2个属性的类(例如,男性/女性)复选框和3个属性.
未来可能会有更多,因此为什么我认为为X量的单选按钮编写一个新类是愚蠢的.
有没有以某种方式使多个属性动态?我看到了一些字典方法.
我看到了这种方法 如何在C#中创建动态属性?
我不知道如何绑定它.
虽然使用C#的动态功能很有趣,但在这种情况下不需要它.良好的老式数据绑定功能足以满足我们的需求.例如.以下是一些ItemsControl使用RadioButton模板将集合绑定到的集合的XAML :
<Grid>
<StackPanel>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
GroupName="Value"
Content="{Binding Description}"
IsChecked="{Binding IsChecked, Mode=TwoWay}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Text="{Binding SelectedItem}"/>
</StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)
以下是在代码隐藏或视图模型中使用它的方法:
DataContext = new CheckBoxValueCollection(new[] { "Foo", "Bar", "Baz" });
Run Code Online (Sandbox Code Playgroud)
现在您只需要集合就可以使它工作.以下是复选框值的集合:
public class CheckBoxValueCollection : ObservableCollection<CheckBoxValue>
{
public CheckBoxValueCollection(IEnumerable<string> values)
{
foreach (var value in values)
{
var checkBoxValue = new CheckBoxValue { Description = value };
checkBoxValue.PropertyChanged += (s, e) => OnPropertyChanged(new PropertyChangedEventArgs("SelectedItem"));
this.Add(checkBoxValue);
}
this[0].IsChecked = true;
}
public string SelectedItem
{
get { return this.First(item => item.IsChecked).Description; }
}
}
Run Code Online (Sandbox Code Playgroud)
以下是复选框值本身:
public class CheckBoxValue : INotifyPropertyChanged
{
private string description;
private bool isChecked;
public string Description
{
get { return description; }
set { description = value; OnPropertyChanged("Description"); }
}
public bool IsChecked
{
get { return isChecked; }
set { isChecked = value; OnPropertyChanged("IsChecked"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您拥有一个完全动态的数据驱动和数据绑定友好的单选按钮设计.
以下是示例程序的样子:

无线电下方的文本显示当前所选项目.虽然在这个例子中我使用了字符串,但您可以轻松地将设计更改为使用enum值或其他来源进行单选按钮描述.