简体   繁体   中英

Listbox Itemsource binding not working

I am trying to bind my list to a listbox. Listbox binding is working but I can't bind property to item template.

Here is my class

public class handle{
        public string smurfName;
        internal Process process;

        public handle(Process _pro, string _smuf)
        {
            process = _pro;
            smurfName = _smuf;
        }
    }

Here is my window constructor.

public static ObservableCollection<handle> smurfList = new ObservableCollection<handle>();
    public GameMask()
        {
            InitializeComponent();
            runningSmurfs.ItemsSource = smurfList;

            handle newSmurf = new handle(null, "THISNAME");
            smurfList.Add(newSmurf);
        }

Here is my xaml

<ListBox HorizontalAlignment="Left" Height="200" Margin="3,41,0,0" VerticalAlignment="Top" Width="113" Name="runningSmurfs">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=smurfName}"></TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Unfortunetely I can't see "THISNAME" on the list, but if I change Texblock Binding to a text it is working fine.

Thank you for your helps.

You need at least a property so your binding can work. smurfName should be a property, better if you implement INotifyPropertyChanged too.

In your case you don't need to implement INotifyPropertyChanged I think, but you can't bind to a field which you were trying to do

Try this:

public string SmurfName { get; set; }

and change in xaml the binding to SmurfName

在您的handle类中,向您的smurfName属性添加一个getter和setter:

public string smurfName { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM