HeaderedItemsControl中的Canvas绑定:Rectangle不显示在绝对位置

时间:2012-02-28 07:28:41

标签: c# wpf xaml mvvm headereditemscontrol

我使用ObservableCollection绑定画布。我需要一个带有TextBlock的Header,它在不同位置的Canvas上都有Title和Rectangles。当用户点击Canvas时,会添加鼠标指针位置的新矩形。

因为我需要Header和Items,所以我使用了HeaderedItemsControl。标题显示正常。 Canvas上添加了Rectangle,但其Left和Top未在给定的绑定位置设置。相反,它是堆叠垂直方向的矩形,我想这是HeaderedItemsControl的默认行为。

XAML -

<HeaderedItemsControl Grid.Column="1" ItemsSource="{Binding Units}">
    <HeaderedItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Canvas.Left="{Binding Position.X}" Canvas.Top="{Binding Position.Y}" 
                                                                        Width="100" Height="70"/>
        </DataTemplate>
    </HeaderedItemsControl.ItemTemplate>
    <HeaderedItemsControl.Header>
        <TextBlock Text="{Binding Title}" />
    </HeaderedItemsControl.Header>
    <HeaderedItemsControl.Template>
        <ControlTemplate TargetType="{x:Type HeaderedItemsControl}">
            <Canvas Background="Transparent" MouseLeftButtonDown="CanvasMouseDown" Cursor="IBeam" >
                <ContentPresenter Content="{TemplateBinding Header}" />
                <ItemsPresenter >

                </ItemsPresenter>
            </Canvas>
        </ControlTemplate>
    </HeaderedItemsControl.Template>
</HeaderedItemsControl>

C#代码背后 -

private void CanvasMouseDown(object sender, MouseButtonEventArgs e)
{
    Point position  = Mouse.GetPosition(e.Source as Canvas);
    MVVM.MainView.Units.Add(
        new MVVM.UnitViewModel(
            new MVVM.UnitModel(), position.X, position.Y));
}

查看模型 -

public class UnitViewModel : WorkspaceViewModel
{
    private UnitModel _unitModel;
    private System.Windows.Point _point;

    internal UnitViewModel(UnitModel unitModel, double x, double y)
    {
        this._unitModel = unitModel;
        _point.X = x;
        _point.Y = y;
    }

    public System.Windows.Point Position
    {
        get { return _point; }
    }
}

您认为问题在哪里?

0 个答案:

没有答案