c# - 图像资源作为图像源不显示
问题描述
我在 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"/>
项目名称是Test
,Spinner
控件位于不同的项目中),没有显示任何内容。
但是,如果我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
解决方案
您的依赖属性声明是错误的,因为CLR 属性包装器的get
/方法必须调用 DependencyObject 基类的和方法(仅此而已)。set
GetValue
SetValue
除此之外,该属性还应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}}"/>
推荐阅读
- pyomo - 如何通过 Pyomo 指定 GAMS 求解器特定的选项?
- node.js - -bash: cdk: command not found ,安装 AWS CDK 后
- android - 在Android中以编程方式隐藏工具栏主页/后退按钮?
- python - __init__ 括号里的东西叫什么?
- matlab - matlab循环通过nxn矩阵陷入无限循环
- php - php中遍历数组的具体问题
- android - 构建 Appbundle (Flutter) 时密钥库密码不正确
- ios - 我可以在滑动手势的途中修复 UINavigationBar 的 TopBar
- php - 正则表达式提取另一个标签内页面上的第一个链接
- android - 在cordova项目上更新到android 7.0.0时出现问题:无法执行aapt