簡體   English   中英

為什么Canvas wpf沒有檢測到點擊?

[英]Why Canvas wpf doesn't detect click?

這是我的XAML

<Window x:Class="Drawing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <TextBox Grid.Row="0" Height="25" IsEnabled="False" Name="txt"/>
    <Canvas Name="cnv" MouseLeftButtonDown="cnv_MouseLeftButtonDown" Grid.Row="1"/>
</Grid>
</Window>

......這是我的C#代碼

private void cnv_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Point p = Mouse.GetPosition(cnv);
    p.X += cnv.Margin.Left;
    p.Y += cnv.Margin.Top;
    txt.Text = p.ToString();
}

問題:

  1. 即使我點擊畫布,事件也沒有被解雇。 我想知道為什么? 我錯過了什么嗎?
  2. 在這段代碼中,我沒有包含任何畫布邊距,但由於我想稍后使用邊距,是否有必要添加帶有邊距的點擊位置以獲得正確的值?

謝謝。

Canvas永遠不會自動調整其大小到內容,即使它確實沒有內容,所以刪除Height="Auto"並讓它填充所有可用空間。 第二個問題是Canvas Background將不會被初始化(默認空值)因此它不會被命中測試可見。 您需要將Background初始化為某些內容,例如Transparent

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Height="25" IsEnabled="False" Name="txt"/>
    <Canvas Name="cnv" MouseLeftButtonDown="cnv_MouseLeftButtonDown" Grid.Row="1" Background="Transparent"/>
</Grid>

編輯

至於第二個問題。 當你GetPosition你指定相對於哪一個元素(在你的情況,你通過cnv ),所以如果你會改變Margincnv它會回報你的位置上,區域的左上角Canvas 您可以通過更改測試MarginBackground ,以紅色為例,的Canvas ,並單擊頂部,紅色矩形的左上角Mouse.GetPosition(cnv)將始終返回你的價值接近於零(不管什么是保證金)

可能有問題

Height="Auto"

行的屬性。 你能嘗試將每個高度設置為175並告訴它是否有幫助嗎?

暫無
暫無

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

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