【问题标题】:Binding to a structure绑定到结构
【发布时间】:2012-02-09 18:09:35
【问题描述】:

我正在尝试将列表视图项绑定到结构的成员,但我无法让它工作。

结构很简单:

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

在我的视图模型中,我保存了这些结构的列表,我希望将“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;
}

我尝试了以下方法,但无法使绑定工作,我需要使用 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>

【问题讨论】:

    标签: wpf listview data-binding


    【解决方案1】:

    您需要在结构属性中创建成员。

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

    我昨天遇到了类似的情况:P

    编辑:哦,是的,就像 Jesse 说的,一旦你把它们变成属性,你就会想要设置 INotifyPropertyChanged 事件。

    【讨论】:

      【解决方案2】:

      你的TextBlock的DataContext是一个DeviceTypeInfo类型的对象,所以你只需要绑定到deviceName,而不是DeviceTypeInfo.deviceName。

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

      此外,您应该绑定到Properties,而不是字段。您可以通过添加{ get; set; } 将字段更改为属性,例如townsean's answer 建议

      【讨论】:

      • @townsean 哈哈,我还是给了你+1,因为你解决了部分问题。
      【解决方案3】:

      我认为你需要 getter 和 setter。您可能还需要实现INotifyPropertyChanged。

      public class ViewModelBase : INotifyPropertyChanged
      {
          public event PropertyChangedEventHandler PropertyChanged;
      
          public void OnPropertyChanged(string propertyName)
          {
              if (PropertyChanged != null)
              {
                  PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-04
        • 2011-12-29
        • 2012-11-13
        • 2018-09-15
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多