簡體   English   中英

WPF - 如何向項目控件添加點擊事件?

[英]WPF - How to add a click event to an items control?

我有這個 ItemsControl:

<ItemsControl Grid.Row="1" ItemsSource="{Binding Board}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="local:Square">
            <Rectangle Stroke="Blue" StrokeThickness="0.5" Width="{Binding Width}" Height="{Binding Height}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

它只是在屏幕上繪制正方形。 我想要一個事件,以便當我單擊它調用該事件的一個正方形時,我還需要獲取我單擊的 object(模板的數據類型是 Square class 並且整個網格綁定到一個可觀察的集合稱為Board ),我該怎么做?

將矩形放在一個Button的模板中,並處理該按鈕的點擊事件。 請記住將矩形的填充設置為透明,否則將無法檢測到在按鈕填充區域中的鼠標單擊。

<Button Click="Rectangle_Click">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Rectangle 
                Fill="Transparent" 
                Stroke="Blue" 
                StrokeThickness="0.5" 
                Width="{Binding Width}" 
                Height="{Binding Height}"
                />
        </ControlTemplate>
    </Button.Template>
</Button>
private void Rectangle_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    var square = button.DataContext as Square;

    //  Do whatever
}

最好給Square一個命令屬性,並將 Button.Command 綁定到該屬性:

public class Square
{
    //  stuff

    public ICommand SelectCommand { get; } // Initialize in constructor

    //  stuff
}
<Button Command="{Binding SelectCommand}">
<!-- ...as before... -->

但是隨后您需要實現 ICommand 等。 Click 事件運行良好。

您還可以在 Rectangle 本身上處理 MouseLeftButtonDown。 您仍然必須將其填充設置為透明。 我更喜歡這個解決方案,因為單擊行為比 MouseLeftButtonDown 更復雜:例如,當您將鼠標放在按鈕上並在釋放鼠標按鈕之前拖出按鈕時,不會引發 Click。 用戶已經習慣了這種行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM