其他分享
首页 > 其他分享> > 在ItemsControl中将View用作DataTemplate时未设置DataContext

在ItemsControl中将View用作DataTemplate时未设置DataContext

作者:互联网

我有一个ViewModels的ObservableCollection,我想绑定到包含关联子Views的ItemsControl.当我将ViewModels添加到集合中时,ItemsControl中会生成适当数量的子视图.但是,每个生成的视图的DataContext为null.如果我插入子视图,则它可以正常工作.因此,我该怎么做才能将我的子视图的DataContext设置为ViewModels?

这是我的父ViewModel中的相关位:

    public ObservableCollection<ChildViewModel> Numbers { get; set; }

    public ParentViewModel()
    {
        Numbers = new ObservableCollection<ChildViewModel>();
    }

    private void ShowNumbers()
    {
        foreach (var num in Enumerable.Range(0, number))
        {
            var childView = new ChildViewModel(number.ToString());
            Numbers.Add(childView);
        }
    }

父视图中的相关位:

        <ItemsControl ItemsSource="{Binding Numbers, UpdateSourceTrigger=PropertyChanged}">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type vm:ChildViewModel}">
                    <v:ChildView />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

儿童观:

<UserControl x:Class="TestWpfApp.Views.ChildView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:prism="http://prismlibrary.com/"             
         prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
    <Label Content="{Binding NumberString}" Width="30" Height="30" BorderThickness="1" BorderBrush="Black" HorizontalAlignment="Center"/>
</Grid>
</UserControl>

子ViewModel:

public class ChildViewModel : BindableBase
{
    private string numberString;
    public string NumberString
    {
        get
        {
            return numberString;
        }
        set
        {
            SetProperty(ref numberString, value);
        }
    }

    public ChildViewModel() { }

    public ChildViewModel(string number)
    {
        NumberString = number;
    }
}

显然,我有一些配置错误的东西,但是我一辈子都无法弄清楚是什么.

仅供参考,我正在使用棱镜库

解决方法:

WPF自动将ItemsControl中的项目容器元素的DataContext设置为适当的项目实例,以便可以将其继承到ItemTemplate中.显然,在设置prism:ViewModelLocator.AutoWireViewModel属性时,将禁用此机制.

因此,只需将其从ChildView的XAML中删除:

<UserControl x:Class="TestWpfApp.Views.ChildView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/">
    <Grid>
        <Label Content="{Binding NumberString}" Width="30" Height="30"
               BorderThickness="1" BorderBrush="Black" HorizontalAlignment="Center" />
    </Grid>
</UserControl>

通常,UserControl绝对不能直接或通过AutoWireViewModel之类的机制显式设置其自己的DataContext,因为这样可以有效地防止从其父控件继承DataContext.

标签:datacontext,wpf,c,mvvm,itemscontrol
来源: https://codeday.me/bug/20191118/2029476.html