How to do dynamic binding with Listbox in silverlight?

隐身守侯 提交于 2019-12-24 11:36:27

问题


I am developing silverlight 4 application. I am using the following listbox for dynamic binding

<ListBox Margin="44,100,46,138" x:Name="lstbox1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding A1}" Foreground="Gray" FontSize="14" Width="100" Height="20" ></TextBlock>
                        <TextBlock Text="{Binding A2}" Foreground="Red" Width="100" Height="20" ></TextBlock>
                        <Line X1="-3400" Y1="32" X2="10" Y2="32" Stroke="Gray" StrokeThickness="1"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I am using the following code in code behind

List<Data1> ObserCollObj = new List<Data1>();
        public MainPage()
        {
            InitializeComponent();
            Data1 obj1 = new Data1("aaa", "dasd");
            ObserCollObj.Add(obj1);
            lstbox1.ItemsSource = ObserCollObj;

        }

I am using the following class

class Data1
    {
        public String A1 { get; set;}
        public String A2 { get; set; }
        public Data1()
        {
        }
        public Data1(String a1, String a2)
        {
            A1 = a1;
            A2 = a2;
        }
    }

I am using all above code but the dynamic binding does not working.Is anything wrong in my xaml or code behind ? Can you please tell me where I am going wrong ? Can you please provide me any solution through which I can resolve the above issue?


回答1:


The initial problem is that the Data1 class needs to be public (currently its internal).

However if you really want dynamic binding then you probably mean that you want to be able to add new entries on the list and for them to appear in the UI.

You should therefore use a ObservableCollection<Data1> instead of a simple List<Data1>.

You may also want to be able to modify the properties of individual entries and have those changes reflected in the UI, to do that you need to implement INotifyPropertyChanged on your Data1 class.



来源:https://stackoverflow.com/questions/6070846/how-to-do-dynamic-binding-with-listbox-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!