簡體   English   中英

在C#中單擊更改邊框內圖像的大小

[英]Change the size of an image inside border on click in c#

當我使用WidthHeight單擊按鈕時,如何在按鈕內部制作圖像以使其更大。

我的Button XAML代碼是這樣的:

<Button x:Name="Input2" Grid.Row="0" MouseEnter="Input2_MouseEnter" MouseLeave="Input2_MouseLeave" Click="Input2_Click" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}">
            <Button.Template>
                <ControlTemplate>
                    <Border HorizontalAlignment="Center" VerticalAlignment="Center" >
                        <Image Source= "C:\input.png"
                           Width="40" 
                           Height="40"/>
                    </Border>
                </ControlTemplate>
            </Button.Template>
</Button>

Input2.Height更改按鈕的大小,而不是按鈕內的圖像。

我的C#代碼:

private void Input2_Click(object sender, RoutedEventArgs e)
{
    // What to do here?
}

與其附加Click事件處理程序,不如對Button的IsPressed屬性使用觸發器:

<Button>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Border>
                <Image x:Name="image" Width="40" Height="40" Source="C:\input.png"/>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter TargetName="image" Property="Width" Value="50"/>
                    <Setter TargetName="image" Property="Height" Value="50"/>
                </Trigger> 
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Button.Template>
</Button>

最簡單的解決方案是將x:Name =“ input2Image”添加到Image元素,並使用該名稱放大圖像,如下所示:

<Button x:Name="Input2" Grid.Row="0" MouseEnter="Input2_MouseEnter" MouseLeave="Input2_MouseLeave" Click="Input2_Click" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}">
        <Button.Template>
            <ControlTemplate>
                <Border HorizontalAlignment="Center" VerticalAlignment="Center" >
                    <Image x:Name="Input2Image" Source= "C:\input.png"
                       Width="40" 
                       Height="40"/>
                </Border>
            </ControlTemplate>
        </Button.Template>

和:

private void Input2_Click(object sender, RoutedEventArgs e)
{
    this.Input2Image.Height = 80;
    this.Input2Image.Width = 80;
}

這應該可行,但是您可以考慮開始使用綁定和MVVM模式,以最大化WPF的功能。

暫無
暫無

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

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