在控件模板中设置属性

3

我想在我的图像控件上分配一个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属性的最佳实践?
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来设置图像的源。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接