如何使用接口而不是具体 class 用作 DataContext - wpf、autofac

how to use interface rather than concrete class to use as DataContext - wpf, autofac

我有下面具体的class和干扰,

public interface IMyViewModel
{
    ObservableCollection<Person> People { get; set; }
}

public class MyViewModel : INotifyPropertyChanged, IMyViewModel
{
    private ObservableCollection<Person> _people;
    public ObservableCollection<Person> People
    {
        get => _people;
        set
        {
            if (value == _people)
                return;

            _people = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        _people = new ObservableCollection<Person>
        {
            new Person() {Id = 1, Name = "Bob", Age = 45},

        };
    }
} 

并为 DI 使用 autofac,

 builder.RegisterType<MyViewModel>().As<IMyViewModel>();

现在在我的 xaml 文件中,我正在尝试绑定列表视图,

<ListView ItemsSource="{Binding People, Mode=OneWay}">
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" Width="100"/>
                <GridViewColumn  Header="Age">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Age}" Width="100"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

在xaml代码后面我想使用接口而不是具体的视图模型class,如何使用这个?

如果我正在使用 DataContext = _viewModel;,那么它不起作用,并且没有记录绑定到列表视图。

 public partial class NetworkConfiguration : Window
{
    private IMyViewModel _viewModel;

    public NetworkConfiguration()
    {
        InitializeComponent();

        //DataContext = new MyViewModel();

        DataContext = _viewModel;
    }

    public IMyViewModel ViewModel
    {
        get
        {
            return _viewModel;
        }
        set
        {
            DataContext = value;
            _viewModel = value;
        }
    }
}

注意 - 如果我使用的是 DataContext = new MyViewModel();,那么它就可以工作。用户界面如何?

谢谢!

    public IMyViewModel ViewModel
    {
        get
        {
            return _viewModel;
        }
        set
        {
            DataContext = value;
            _viewModel = value;
        }
    }

您需要实际为 ViewModel 分配容器中的值:


      var builder = new ContainerBuilder();
      builder.RegisterType<MyViewModel>().As<IMyViewModel>();

      // This is your container, here you can get your instances from!
      Container = builder.Build();

      // Create the scope, resolve your interface,
      // use it, then dispose of the scope.
      using (var scope = Container.BeginLifetimeScope())
      {
         // get the vm from the container, assign it as datacontext.
         DataContext = scope.Resolve<IMyViewModel >();

      }