Reputation: 129
I have created my own radiobutton to include index property as following:
public class IndexedRadioButton : RadioButton
{
public int Index { get; set; }
}
I am using this custom radio button in a list box:
<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>
Now, I want to fill this list box with values.
Code behind:
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; }
}
}
When I run the app, I get this error ->>{System.ArgumentException: Value does not fall within the expected range.} (No stack trace info)
What do you think is causing the error? There is no problem when I set some value to Index staticly in XAML Index="0"
but there is a problem in binding Index="{Binding priceIndex}"
.
Thanks,
Upvotes: 0
Views: 766
Reputation: 6424
In order to allow bindings, you have to declare a Dependency Property. Try this:
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); }
}
}
You'll find more info here:
Dependency properties for Windows Phone
Upvotes: 1