具有Dependency属性的按钮用户控件ShowImage显示图像路径而不是Image

时间:2015-02-23 10:27:51

标签: c# wpf

我正在尝试创建一个按钮用户控件,它可以通过添加属性(ShowImage =“ImagePath”)显示来自xaml的图像。 我已将用户控件Image源绑定到xaml文件中按钮的Content:

<UserControl x:Class="testUserControl.UserControls.TestDependencyShowImage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             Height="auto" Width="auto">
    <Grid>
        <Button MinHeight="30" MinWidth="50">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Image Source="{TemplateBinding Content}"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</UserControl>

我创建了一个Dependency属性,它创建了BitmapImage并将其设置为内容(同时硬编码路径只是为了查看是否可以完成)。

CS:

namespace testUserControl.UserControls
{
    /// <summary>
    /// Interaction logic for TestDependencyShowImage.xaml
    /// </summary>
    public partial class TestDependencyShowImage : UserControl
    {
        private static BitmapImage  s_oImage            = null;
        private static string       s_strSourceImage    = null;

        public static readonly DependencyProperty ShowImageDP = DependencyProperty.Register("ShowImage", typeof(string), typeof(TestDependencyShowImage), new PropertyMetadata(null, new PropertyChangedCallback(SetImage)));

        public string ShowImage
        {
            get
            {
                return (string)GetValue(ShowImageDP);
            }
            set
            {
                SetValue(ShowImageDP, value);
                this.Content = s_oImage;
                //OnTargetPowerChanged(this, new DependencyPropertyChangedEventArgs(TargetPowerProperty, value, value));    // Old value irrelevant.
            }
        }

        private static void SetImage(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            TestDependencyShowImage muc = (TestDependencyShowImage)obj;
            s_strSourceImage = (string)args.NewValue;
            if (s_strSourceImage != null)
            {
                s_oImage = new BitmapImage(new Uri(@"C:\Users\AmitL\Desktop\james-brown-010.jpg", UriKind.Absolute));
                //BitmapImage l_oImage = new BitmapImage(new Uri(value));
            }

        }


        public TestDependencyShowImage()
        {
            InitializeComponent();
            this.Content = s_oImage;
        }
    }
}

no image!

1 个答案:

答案 0 :(得分:0)

你真的不需要任何代码。让框架将string文件路径转换为图像。在UserControl

中试用此代码
<Image Source="{Binding ShowImage, RelativeSource={RelativeSource 
    AncestorType={x:Type YourXamlNamespacePrefix:TestDependencyShowImage}}}" />