【问题标题】:Difference between binding object/properties in ListView and ListBoxListView 和 ListBox 中绑定对象/属性的区别
【发布时间】:2013-09-19 17:22:56
【问题描述】:

我有一个 ListView,它显示员工列表,并且每个 SelectionChanged 事件在一组文本框中显示有关每个员工的不同信息。

<ListView ItemsSource="{Binding Employees}" x:Name="lvEmployeeList" Grid.Row="1" Grid.Column="1" Width="385" SelectedIndex="0" Margin="1,1,1,1" >
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="SelectionChanged">
                        <i:InvokeCommandAction Command="{Binding ProcessCommand}" CommandParameter="{Binding ElementName=lvEmployeeList, Path=SelectedItem.EmployeeID}" ></i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>

效果很好。然后我想了解 DataTemplate 所以这次我使用了一个 ListBox 并在 Listbox 中再次显示信息(只是一个简单的版本,它在列表框的每一行中显示几个字段)问题是当 SelectionChanged 发生时我得到一个运行时错误为

对象引用未设置为对象的实例

    <ListBox x:Name="lstEmployees" ItemsSource="{Binding Employees}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding EmployeeID}" />
                    <TextBlock Text="{Binding BackgroundID}" />
                    <TextBlock Text="{Binding EmployeeName}" />
                </StackPanel>                        
            </DataTemplate>
        </ListBox.ItemTemplate>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding ProcessCommand}" CommandParameter="{Binding ElementName=lstEmployee, Path=SelectedItem.EmployeeID}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ListBox>

基本上在 ViewModel 中我有一个 linq 语句:

PropertyEmployee = Employees.FirstOrDefault(item => item.EmployeeID == param.ToString());  

你能告诉我是什么导致了这个错误吗?在 ListView 中很好,但在 ListBox 中我得到的是空对象。

【问题讨论】:

    标签: c# linq listview listbox datatemplate


    【解决方案1】:

    我能够通过在我的视图模型中添加一个选定的属性来克服这个问题

    public Employee SelectedEmployee { get; set; }
    

    然后以OneWayToSource 模式将 SelectedItem 绑定到该属性

    <ListBox x:Name="lstEmployees" ItemsSource="{Binding Employees}" SelectionMode="Single" SelectedItem="{Binding Path=SelectedEmployee, Mode=OneWayToSource}">
    

    使ProcessCommand不带参数

    <i:InvokeCommandAction Command="{Binding ProcessCommand}"/>
    

    最后,在ProcessCommand 执行中,检索您的Employee id 并从那里做任何事情......

    var id = SelectedEmployee.EmployeeId;
    
    // Do whatever you want
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2017-04-08
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      相关资源
      最近更新 更多