首页 > 解决方案 > 图像资源作为图像源不显示

问题描述

我在 WPF UserContol 库中定义了一个自定义加载微调器 UserControl。它有一个依赖属性:

public string SpinnerSourcePath { get => _spinner.Source.ToString(); set => _spinner.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(value); }

public static readonly DependencyProperty SpinnerSourcePathProperty =
            DependencyProperty.Register(nameof(SpinnerSourcePath), typeof(string), typeof(Spinner));

_spinner在哪里Image
(我直接在ImageSource课堂上尝试过,但没有骰子)

xaml 看起来像这样:

<Image x:Name="_spinner" RenderTransformOrigin="0.5 0.5">
    <SomeStyleToMakeItRotate.../>
</Image>

我通过定义它来使用它:(
<c:Spinner SpinnerSourcePath="/Test;component/_Resources/loading.png"/>
项目名称是TestSpinner控件位于不同的项目中),没有显示任何内容。

但是,如果我Source直接在Spinner定义中添加属性:

<Image x:Name="_spinner" Source="/Test;component/_Resources/loading.png" RenderTransformOrigin="0.5 0.5">
    <SomeStyleToMakeItRotate.../>
</Image>

它正确显示...

这让我相信依赖属性是错误的,但是如何呢?

E1:

在尝试对不同的控件执行相同的步骤后,它再次停止工作。

这次我有一个DP:

public static readonly DependencyProperty ValidationFunctionProperty =
    DependencyProperty.Register(nameof(ValidationFunction), typeof(Func<string, bool>), typeof(ValidatedTextBox), new PropertyMetadata(OnAssignValidation));

public Func<string, bool> ValidationFunction {
    get => (Func<string, bool>)GetValue(ValidationFunctionProperty);
    set => SetValue(ValidationFunctionProperty, value);
}

private static void OnAssignValidation(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    Debugger.Break();
}

控制使用:

<c:ValidatedTextBox x:Name="valid"
                    Text="Test"
                    ValidationFunction="{Binding Validation, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource test}}"/>

转换器只是一个Debugger.Break()并返回原件

最后RelativeSource控制权是我的MainWindow

public MainWindow() {
    InitializeComponent();
}

public Func<string,bool> Validation => (s) => true;

(DP也有问题Text,但我想我可以自己解决)

E2

Ok Pro 问题是RelativePath指向UserControl但它被放置在Window

标签: c#wpfimage

解决方案


您的依赖属性声明是错误的,因为CLR 属性包装器的get/方法必须调用 DependencyObject 基类的和方法(仅此而已)。setGetValueSetValue

除此之外,该属性还应ImageSource用作其类型:

public static readonly DependencyProperty SpinnerSourceProperty =
    DependencyProperty.Register(
        nameof(SpinnerSource), typeof(ImageSource), typeof(Spinner));

public ImageSource SpinnerSource
{
    get { return (ImageSource)GetValue(SpinnerSourceProperty); }
    set { SetValue(SpinnerSourceProperty, value); }
}

UserControl 的 XAML 中的 Image 元素将使用如下属性:

<Image Source="{Binding SpinnerSource,
                RelativeSource={RelativeSource AncestorType=UserControl}}"/>

推荐阅读