Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to a structure

I am trying to bind a listview item to a member of a structure, but I am unable to get it to work.

The structure is quite simple:

public struct DeviceTypeInfo
{
    public String deviceName;
    public int deviceReferenceID;
};

in my view model I hold a list of these structures and I want to get the "deviceName" to be displayed in a list box.

public class DevicesListViewModel
{
    public DevicesListViewModel( )
    {

    }

    public void setListOfAvailableDevices(List<DeviceTypeInfo> devicesList)
    {
        m_availableDevices = devicesList;
    }

    public List<DeviceTypeInfo> Devices
    {
        get { return m_availableDevices; }
    }

    private List<DeviceTypeInfo> m_availableDevices;
}

I have tried the following but I can't get the binding to work, do I need to use relativesource?

    <ListBox Name="DevicesListView" Grid.Column="0" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="10"  MinHeight="250" MinWidth="150"  ItemsSource="{Binding Devices}" Width="Auto">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding DeviceTypeInfo.deviceName}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
like image 209
user1145533 Avatar asked Feb 09 '12 18:02

user1145533


3 Answers

You need to make the members in the struct properties.

public struct DeviceTypeInfo 
{    
    public String deviceName { get; set; }     
    public int deviceReferenceID { get; set; } 
}; 

I ran into a similar situation yesterday :P

EDIT: Oh yeah, and like Jesse said, once you turn them into properties, you'll want to set up the INotifyPropertyChanged event.

like image 185
Ashley Grenon Avatar answered Sep 30 '22 13:09

Ashley Grenon


Your TextBlock's DataContext is an object of type DeviceTypeInfo, so you only need to bind to deviceName, not DeviceTypeInfo.deviceName.

<DataTemplate>
    <StackPanel Orientation="Vertical">
        <TextBlock Text="{Binding deviceName}"/>
    </StackPanel>
</DataTemplate>

In addition, you should be binding to Properties, not fields. You can change your fields to properties by adding { get; set; } to them like the other answer suggests

like image 21
Rachel Avatar answered Sep 30 '22 14:09

Rachel


I think you need getters and setters. You also might need to implement INotifyPropertyChanged.

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
like image 21
Jesse Seger Avatar answered Sep 30 '22 14:09

Jesse Seger