C# 具有依赖属性ShowImage的按钮用户控件显示图像路径而不是图像

C# 具有依赖属性ShowImage的按钮用户控件显示图像路径而不是图像,c#,wpf,C#,Wpf,我正在尝试创建一个按钮用户控件,它可以通过添加属性(ShowImage=“ImagePath”)来显示来自xaml的图像。 我已将用户控件图像源绑定到xaml文件中按钮的内容: <UserControl x:Class="testUserControl.UserControls.TestDependencyShowImage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

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

<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>

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

政务司司长:

namespace testUserControl.UserControls
{
/// 
///TestDependencyShowImage.xaml的交互逻辑
/// 
公共部分类TestDependencyShowImage:UserControl
{
私有静态位图图像s_oImage=null;
私有静态字符串s_strSourceImage=null;
public static readonly dependencProperty ShowImageDP=dependencProperty.Register(“ShowImage”、typeof(string)、typeof(TestDependencyShowImage)、newPropertyMetadata(null、newPropertyChangedCallback(SetImage));
公共字符串显示图像
{
得到
{
返回(字符串)GetValue(ShowImageDP);
}
设置
{
设置值(ShowImageDP,值);
this.Content=s_oImage;
//OnTargetPowerChanged(这是新的DependencyPropertyChangedEventArgs(TargetPowerProperty,value,value));//旧值不相关。
}
}
私有静态void SetImage(DependencyObject对象、DependencyPropertyChangedEventArgs参数)
{
TestDependencyShowImage muc=(TestDependencyShowImage)obj;
s_strSourceImage=(字符串)args.NewValue;
如果(s_strSourceImage!=null)
{
s_oImage=新位图图像(新Uri(@“C:\Users\AmitL\Desktop\james-brown-010.jpg”,UriKind.Absolute));
//BitmapImage l_oImage=新的BitmapImage(新的Uri(值));
}
}
公共TestDependencyShowImage()
{
初始化组件();
this.Content=s_oImage;
}
}
}

你真的不需要这些代码。只需让框架为您将
字符串
文件路径转换为图像即可。在
用户控件中尝试此代码:

<Image Source="{Binding ShowImage, RelativeSource={RelativeSource 
    AncestorType={x:Type YourXamlNamespacePrefix:TestDependencyShowImage}}}" />


这里有很多错误。首先,您不能在code behind中设置UserControl的
Content
属性,因为这将替换由其XAML创建的所有内容。UserControl的内容包含来自其XAML的顶级Grif,您不会对此进行更改。也就是说,按钮的ControlTemplate中的
{TemplateBinding Content}
引用的是按钮的内容,而不是UserControl中的内容。接下来,在依赖项属性的CLR包装器中,除了GetValue/SetValue之外,决不能执行任何操作。为响应更改的属性值而应调用的所有必要代码都应位于PropertyChangedCallback中。请参阅以了解更多详细信息。如果这一切都是关于创建一个以图像作为其内容的按钮,那么为什么不这样做呢?创建按钮,并将其内容属性设置为BitmapImage。不需要用户控件。
<Image Source="{Binding ShowImage, RelativeSource={RelativeSource 
    AncestorType={x:Type YourXamlNamespacePrefix:TestDependencyShowImage}}}" />