0

我有一个模型:

public class Table : ViewModelBase
{
    private int _id;
    private string _north;
    private string _east;
    private string _south;
    private string _west;

    public int Id
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value; OnPropertyChanged();
        }
    }

    public string North
    {
        get { return _north; }
        set { _north = value; OnPropertyChanged();}
    }

    public string East
    {
        get { return _east; }
        set { _east = value; OnPropertyChanged();}
    }

    public string South
    {
        get { return _south; }
        set { _south = value; OnPropertyChanged();}
    }

    public string West
    {
        get { return _west; }
        set { _west = value; OnPropertyChanged();}
    }
}

还声明了表列表的 ViewModel:

            Tables = new ObservableCollection<Table>();

在 XAML 中:

<ScrollViewer.Resources>
                <ItemsPanelTemplate x:Name="MyWrapPanel">
                    <toolkit:WrapPanel MinWidth="250" Width="{Binding ViewportWidth, ElementName=MyScrollViewer}" />
                </ItemsPanelTemplate>
            </ScrollViewer.Resources>

            <ItemsControl ItemsSource="{Binding Tables}" ItemsPanel="{StaticResource MyWrapPanel}" Grid.RowSpan="2" Grid.Row="1">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <controls:TableControl 
                            TableNumber="{Binding Id}"
                            North="{Binding North}"
                            East="{Binding East}"
                            South="{Binding South}"
                            West="{Binding West}"
                            />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

        </ScrollViewer>

但是当我将元素添加到表格列表时,一切正常。但

TableNumber="{Binding Id}"
North="{Binding North}"
East="{Binding East}"
South="{Binding South}"
West="{Binding West}"

确实不受约束。

4

1 回答 1

0

Xaml名为 的用户控件的文件中TableControl,添加DataContext={Binding} 根元素,我认为它应该可以工作(如果它不存在)。

如果您在用户控件(例如)文件后面的代码中DataContext设置了类似使用户控件不使用集合的 DataContext 的内容,它也可能无法正常工作。TableControl.xaml.csthis.DataContext = this;Tables

您可以使用此 SO Answer来检查用户控件的 DataContext 中的确切内容TableControl

编辑:

也试试下面,因为根据您的评论,DataContext forTableControl是冲突的:

<DataTemplate>
    <controls:TableControl DataContext="{Binding}" 
        TableNumber="{Binding Id}"
        North="{Binding North}"
        East="{Binding East}"
        South="{Binding South}"
        West="{Binding West}"
        />
</DataTemplate>
于 2013-09-13T19:45:00.830 回答