如何将ListView.SelectedItem属性绑定到MVVM中的ViewModel?

时间:2017-07-31 18:29:30

标签: c# xaml mvvm uwp

我目前正在开发一个UWP MVVM项目,要求最终用户从列表中选择一个项目,然后单击一个按钮。按钮及其链接的命令使用SelectedItem属性来检测最终用户想要编辑或删除的对象。我正在使用Fody的MVVM模式(因此已经实现了INotificationPropertyChanged)。问题是没有按钮,也没有它们的功能,因为属性总是返回" null"。

这是XAML视图:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js"></script>
 <script src="https://code.angularjs.org/1.2.0rc1/angular-route.js"></script>

我的ViewModel:

<ListView ItemsSource = "{x:Bind ViewModel.EmployeeListing, Mode=OneWay}" SelectedItem="{x:Bind ViewModel.SelectedEmployee, Mode=TwoWay, Converter={StaticResource ObjectToEmployeeConverter}}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="models:Employee">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width = "auto" />
                </ Grid.ColumnDefinitions >
                < TextBlock Grid.Column="0" Style="{StaticResource BodyTextBlockStyle}" Text="{x:Bind DisplayName, Mode=OneWay}">
                </TextBlock>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Footer>
        <StackPanel Orientation = "Horizontal" >
            < Button Margin="8" x:Uid="Employees_Edit" Command="{x:Bind ViewModel.EditEmployeeCommand}" IsEnabled="{x:Bind ViewModel.IsEmployeeSelected}"/>
            <Button Margin = "8" x:Uid="Employees_Remove" Command="{x:Bind ViewModel.RemoveEmployeeCommand}" IsEnabled="{x:Bind ViewModel.IsEmployeeSelected}"/>
            <Button Margin = "8" x:Uid="Employees_Add" Command="{x:Bind ViewModel.NewEmployeeCommand}"/>
        </StackPanel>
    </ListView.Footer>
</ListView>

最后,我的转换器:

[AddINotifyPropertyChangedInterface]
public class EmployeesViewModel
{
    public ObservableCollection<Employee> EmployeeListing { get; set; }

    public Employee SelectedEmployee { get; set; } //NOT currently responding to change in selected item

    public bool IsNewEmployee; //True if creating a chart of account. False is editing one.
    public Employee NewEmployeeBuffer; //Used when creating a new accont (Discarded if Cancel, Added if Save)

    public bool IsEmployeeSelected
    {
        get
        {
            return SelectedEmployee != null;
        }
    }
    public ICommand EditEmployeeCommand;
    public ICommand RemoveEmployeeCommand;
    public ICommand NewEmployeeCommand;
    public ICommand SaveEditedEmployeeCommand;
    public ICommand CancelCommand;

    public EmployeesViewModel()
    {
        Task.Run(SetEmployeeListing).Wait();
    }
    private async Task SetEmployeeListing()
    {
        EmployeeListing = await Employee.EmployeeListing();
    }
}

我非常感谢任何帮助。我已经被困了一段时间

0 个答案:

没有答案