我正在努力学习原则,并在wpf中创建一个独立的用户控件,然后可以在将来的项目中使用。
我在这个控件中有几个按钮,每个按钮都有一个图像属性,定义为依赖属性,允许最终用户使用他们喜欢的任何图像。
在xaml中按钮的定义如下:
<Button Background="#00000000" x:Name="First" Height="Auto" Width="Auto" ToolTip="Go to First Record.">
<StackPanel Margin="2" Orientation="Horizontal">
<Image Source="{Binding ImageFirst, ElementName=DN}"
Width="{Binding ImageFirstWidth, ElementName=DN}"
Height="{Binding ImageFirstHeight, ElementName=DN}"/>
<TextBlock Margin="3" Text="{Binding TextFirst,ElementName=DN}"/>
</StackPanel>
</Button>
,因此定义了相应的图像依赖属性:
Public Property ImageFirst() As ImageSource
Get
Return DirectCast(GetValue(ImageFirstProperty), ImageSource)
End Get
Set(value As ImageSource)
SetValue(ImageFirstProperty, value)
End Set
End Property
Public Shared ReadOnly ImageFirstProperty As DependencyProperty = DependencyProperty.Register("ImageFirst", GetType(ImageSource), GetType(DataNavigator), New UIPropertyMetadata(Nothing))
此功能完全符合预期,让最终用户有机会选择他们为按钮选择的任何图像。
我现在要做的是为butoons添加一组默认图像。我在项目中创建了一个文件夹(想象中称为“图像”),我添加了一组图像作为默认值。我是否正确地认为,如果我将依赖属性声明的UIPropertyMetadata部分从无变为对这些图像之一的引用,则该图像将被用作默认值但仍然允许最终用户选择另一个如果他们选择。 / p>
如果是这种情况,我该如何定义UIPropertMetadata部分。我尝试了UIPropertyMetadata(“\ Images \ first16.png”),但似乎无法正常工作。
非常感谢您提出的任何建议。
答案 0 :(得分:0)
设置默认图像有点复杂。您需要使用正确初始化的Uri创建BitmapImage类的对象。这就是我在代码中的方式:
private static readonly ImageSource DefaultImage = new BitmapImage(new Uri("pack://application:,,,/MyAppNamespace;component/Images/default.png",UriKind.RelativeOrAbsolute));
public static readonly DependencyProperty PictureSourceProperty = DependencyProperty.Register("PictureSource", typeof (ImageSource), typeof (RecordPicture), new PropertyMetadata(DefaultImage));
public ImageSource PictureSource
{
get { return (ImageSource) GetValue(PictureSourceProperty); }
set { SetValue(PictureSourceProperty, value); }
}