use*_*533 7 data-binding wpf listview
我试图将listview项绑定到结构的成员,但我无法让它工作.
结构很简单:
public struct DeviceTypeInfo
{
public String deviceName;
public int deviceReferenceID;
};
Run Code Online (Sandbox Code Playgroud)
在我的视图模型中,我保存了这些结构的列表,我想让"deviceName"显示在列表框中.
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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过以下但是我无法使绑定工作,我需要使用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>
Run Code Online (Sandbox Code Playgroud)
Ash*_*non 15
您需要在struct属性中创建成员.
public struct DeviceTypeInfo
{
public String deviceName { get; set; }
public int deviceReferenceID { get; set; }
};
Run Code Online (Sandbox Code Playgroud)
昨天我遇到了类似的情况:P
编辑:哦是的,就像杰西说的那样,一旦你把它们变成属性,你就会想要设置INotifyPropertyChanged事件.
我认为你需要 getter 和 setter。您可能还需要实施INotifyPropertyChanged.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的 TextBlockDataContext是一个类型的对象DeviceTypeInfo,所以你只需要绑定到deviceName,而不是DeviceTypeInfo.deviceName。
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding deviceName}"/>
</StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
此外,您应该绑定到Properties,而不是字段。您可以{ get; set; }像townsean 的回答所建议的那样通过添加字段来将字段更改为属性
| 归档时间: |
|
| 查看次数: |
10086 次 |
| 最近记录: |