将值绑定到列表框项模板(WP8)中的自定义单选按钮

时间:2013-06-06 14:38:36

标签: c# xaml binding listbox windows-phone

我创建了自己的单选按钮以包含索引属性,如下所示:

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

    }

当我运行应用时,我收到此错误 - &gt;&gt; {System.ArgumentException:值不在预期范围内。}(无堆栈跟踪信息)

您认为导致错误的是什么?在XAML Index="0"中静态设置一些值时,没有问题,但绑定Index="{Binding priceIndex}"时出现问题。

谢谢,

1 个答案:

答案 0 :(得分:1)

为了允许绑定,您必须声明一个依赖属性。试试这个:

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

}

您可以在此处找到更多信息:

Dependency properties for Windows Phone