1

ListView用来显示Buttons 的列表。在使用StackPanelorWrapPanelItemsPanelListView一切正常。当我只尝试Canvas集合中的最后一个按钮正在工作时,其他人甚至不会在鼠标悬停时改变他们的背景。我可以让它们都正常工作吗?

<ListView ItemsSource="{Binding collection1}">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Button Margin="{Binding margin}" Width="40" Height="40" Click=button_click />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

后面的代码:

public class object1
{
    public double x0 { get; set; }
    public double y0 { get; set; }
    public Thickness margin { get { return new Thickness(x0, y0, 0, 0); } }

    public object1(double x, double y)
    {
        x0= x;
        y0 = y;
    }
}

public MainWindow : Window
{
    public ObservableCollection<object1> collection1 {get;set;}

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;     

        collection1=new ObservableCollection<object1>();
        collection1.Add(new object1(20,20));
        collection1.Add(new object1(20,80));
        collection1.Add(new object1(80,20));
        collection1.Add(new object1(80,80)); // ONLY THAT ONE WORKS
    }
 }
4

1 回答 1

1

问题在于您Margin使用ListViewItem. 所有的 ListViewItems 在 Canvas 中相互重叠,只有最上面的才能获取输入事件。

将 Margin 绑定从 a 中移出ItemTemplateItemContainerStyle以便它设置MarginaListViewItem而不是 a Button

<ListView>
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Margin" Value="{Binding margin}"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Button Width="40" Height="40" .../>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

当使用 a 时CanvasItemsPanel我强烈建议使用Canvas.LeftandCanvas.Top属性来定位项目容器。您通常会将它们绑定到数据项类型的属性,例如您的x0and y0

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="Canvas.Left" Value="{Binding x0}"/>
        <Setter Property="Canvas.Top" Value="{Binding y0}"/>
    </Style>
</ListView.ItemContainerStyle>
于 2013-10-17T11:43:06.487 回答