在控件模板中设置属性

时间:2013-03-06 08:55:56

标签: c# silverlight xaml

我想在我的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属性的最佳做法是什么?

1 个答案:

答案 0 :(得分: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来设置图像的来源。

相关问题