2017-08-31 80 views
1

我有一個畫布作爲ItemsPanel的列表框。帶畫布的WPF列表框只顯示最後一項

<UserControl.Resources> 
    <DataTemplate x:Key="itemTemplate"> 
     <Border BorderBrush="LightBlue" BorderThickness="1"> 
      <Grid Margin="0,2,2,2" Width="{Binding Width}" Height="{Binding Height}"> 
       <Rectangle Cursor="Hand" Fill="AliceBlue" 
         MouseDown="Rectangle_MouseDown" 
         MouseMove="Rectangle_MouseMove" 
         MouseUp="Rectangle_MouseUp"/> 
       <Label Content="{Binding Name}" Margin="5" IsHitTestVisible="False"/> 
      </Grid> 
     </Border> 
    </DataTemplate> 
</UserControl.Resources> 

<ListBox ItemsSource="{Binding Items}" 
     x:Name="listBox" 
     SelectionMode="Extended" 
     ItemTemplate="{StaticResource itemTemplate}"> 


    <ListBox.ItemsPanel> 
     <ItemsPanelTemplate> 
      <Canvas Background="Transparent"/> 
     </ItemsPanelTemplate> 
    </ListBox.ItemsPanel> 

    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="Canvas.Left" Value="{Binding X}"/> 
      <Setter Property="Canvas.Top" Value="{Binding Y}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

問題是,無論何時我將新項目添加到項目,哪個Listbox綁定到,它只顯示屏幕上的新項目。列表中的所有以前的項目都未顯示。我可以看到所有的項目確實在Items列表中,並且ListBoxItems被添加到可視化樹中。但我看不到他們。只添加最後一項。

這是什麼樣子的運行(僅過一個項目顯示)

enter image description here

這是什麼樣子的設計師,它看起來應該像跑步

enter image description here

有什麼建議嗎?

更新1

的設計人員使用的代碼是這個

public class DrawingPanelViewModelMockup: DrawingPanelViewModel 
{ 
    public DrawingPanelViewModelMockup() 
    { 
     //Pc subclasses DrawingComponent 
     var pc = new Pc(); 
     pc.Name = "PC"; 
     pc.X = 20; 
     pc.Y = 40; 
     pc.Width = 100; 
     pc.Height = 50; 
     Items.Add(pc); 

     ... 

    } 
} 

而且,增加了項目(的ObservableCollection)真正的代碼是這樣的。它是拖放式操作的一部分。

var comp = e.Data.GetData(typeof(DrawingComponent).FullName) as DrawingComponent; 
var drawingPanelVm = ServiceLocator.Current.GetInstance<DrawingPanelViewModel>(); 
comp.X = mousePos.X; 
comp.Y = mousePos.Y; 
comp.Width = 100; 
comp.Height = 50; 
drawingPanelVm.Items.Add(comp); 
+0

Is Items a List or ObservableCollection?你的代碼適合我。 –

+1

您還應該顯示實際添加項目的代碼。它與設計模式代碼有什麼不同? – Clemens

+0

@EdPlunkett這是一個ObservableCollection,請參閱我的更新 – smok

回答

1

的XAML正常工作,並且已經確認,只有一個創建的視圖模型的副本,因此只有一個Items收集,並首次下降作品。

看你的代碼,什麼跳出我是這一行:

var comp = e.Data.GetData(typeof(DrawingComponent).FullName) as DrawingComponent; 

那不是創造一個DrawingComponent;它正在將其中一件東西放入其中。我在那裏放置了一個斷點,看看你是否真的獲得了Items中的多個項目,但它們都是相同的實際對象實例,具有相同的屬性值。

或者我只是直奔代碼開始的阻力,並確保你正在創建一個新的DrawingComponent每次 - 或者創建一個克隆的下降結束各一次。雖然在拖動結束時執行它似乎更好,因爲可以從不同的源拖動不同的子類DrawingComponent,並且放下代碼不需要擔心。

相關問題