获取按钮sender ImageBrush.ImageSource从XAML

本文关键字:XAML ImageSource ImageBrush 按钮 sender 获取 | 更新日期: 2023-09-27 18:08:36

首先,我有多个按钮,将我发送到另一个页面,我希望在第二页上显示此按钮的ImageBrush。像x:Name, TagContent这样的字段已经很忙了,所以我不能使用它们。我的按钮是这样的:

XAML

<Button x:Name="but01" Click="Button2_Click" Tag="this tag is bussy" Content="First Button" >
    <Button.Background>
        <ImageBrush x:Name="brush1" ImageSource="/Assets/Logos/1.png" Stretch="Uniform" />
    </Button.Background>
</Button>

背后的代码:

private void Button2_Click(object sender, EventArgs e)
{
    //this is what I've tried
    var brush = new ImageBrush();
    brush = (ImageBrush)((sender as Button).Background);
    string mynew = brush.ImageSource.ToString();
    NavigationService.Navigate(
        new Uri("/MainPage.xaml?path=" +
                HttpUtility.UrlEncode((sender as Button).Tag.ToString())+ "&source="+ mynew,
                UriKind.Relative));
}

mynew = System.Windows.Media.Imaging.BitmapImage的地方我希望它是:/Assets/Logos/1.png

任何想法?也许除了Tag, NameContent,还有其他字段可以存储这个路径?

获取按钮sender ImageBrush.ImageSource从XAML

您应该使用BitmapImage而不是ImageSource

您可以像这样获得图像路径:

var brush = but01.Background as ImageBrush;
BitmapImage source = brush.ImageSource as BitmapImage;
Uri uri = source.UriSource;
string uriStr = uri.OriginalString;

字段uriStr是您想要的值!