[英]Binding value to custom radio button in list box item template (WP8)
我创建了自己的单选按钮以包含索引属性,如下所示:
public class IndexedRadioButton : RadioButton
{
public int Index { get; set; }
}
我在列表框中使用此自定义单选按钮:
<ListBox Name="myListBox" Grid.Row="1" VerticalAlignment="Top">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" >
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<my:IndexedRadioButton Content="{Binding price}" GroupName="myGroup" IsChecked="{Binding isChecked}" Index="{Binding priceIndex}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在,我想用值填充此列表框。
后面的代码:
public MainClass()
{
public MainClass()
{
InitializeComponent();
string[] priceList = new string["1","2","3"];
List<MyClass> myClassList = new List<MyClass>();
for (int i = 0; i < priceList.Count; i++)
{
MyClass listClass = new MyClass()
{
price = response.priceList[i],
priceIndex = i,
isChecked = i==0?true:false
};
myClassList.Add(listClass);
}
myListBox.ItemsSource = myClassList;
}
private class MyClass
{
public string price {get; set;}
public int priceIndex {get; set;}
public bool isChecked { get; set; }
}
}
运行应用程序时,出现此错误->> {System.ArgumentException:值不在预期范围内。}(无堆栈跟踪信息)
您认为是什么导致了错误? 当我在XAML Index="0"
中将某些值静态设置为Index时没有问题,但是在绑定Index="{Binding priceIndex}"
。
谢谢,
为了允许绑定,您必须声明一个Dependency属性。 尝试这个:
public class IndexedRadioButton : RadioButton
{
public static readonly DependencyProperty IndexProperty = DependencyProperty.Register(
"Index",
typeof(int),
typeof(IndexedRadioButton),
null);
public int Index
{
get { return (int)GetValue(IndexProperty); }
set { SetValue(IndexProperty, value); }
}
}
您可以在此处找到更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.