3

我想在我的 Image 控件上分配一个 URI。以下 XAML 位于 UserControl 中。

<StackPanel>
    <Button Command="{StaticResource ImageClick}" x:Name="imageButton">
        <Button.Template>
            <ControlTemplate>
                <Grid>
                    <Image MaxHeight="100" MaxWidth="300" x:Name="image" />
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
</StackPanel>

我在代码隐藏了一个带有图像 URL 的依赖属性:

public string ImageUrl
{
    get { return (string)GetValue(ImageUrlProperty); }
    set { SetValue(ImageUrlProperty, value); }
}

// Using a DependencyProperty as the backing store for ImageUrl.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty ImageUrlProperty =
    DependencyProperty.Register("ImageUrl", typeof(string), typeof(ImageControl), new PropertyMetadata(""));

分配 ControlTemplate 中的 Image 的 Source 属性的最佳做法是什么?

4

1 回答 1

1

您可以使用内容展示器,然后仅将您的图像放入按钮的内容中。

<StackPanel>
    <Button Command="{StaticResource ImageClick}"
        x:Name="imageButton">
        <Button.Template>
            <ControlTemplate>
                <Grid>
                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </Button.Template>
        <Image MaxHeight="100"
               MaxWidth="300"
               x:Name="image" />
    </Button>
</StackPanel>

在您的代码中使用 PropertyChangedCallback 来设置图像的来源。

于 2013-03-06T09:16:57.017 回答