这是我缩短的buttonStyle:
<Style x:Key="ToolbarbuttonStyle" targettype="button"> ... <Image x:name="toolbarImage" Source="{TemplateBinding PrismExt:ImageSourceAttachable:ImageSource}" WIDth="48" Height="48" /> ...</Style>
这是附加的属性定义,请注意,我不知道如何修复回调,因为dependencyproperty似乎是按钮而不是图像。而button并没有将我的图像暴露在其风格之内。这很棘手。
namespace SalesContactManagement.Infrastructure.PrismExt{ public class imgSourceAttachable { public static voID SetimgSource(DependencyObject obj,string imgSource) { obj.SetValue(imgSourceProperty,imgSource); } public static string GetimgSource(DependencyObject obj) { return obj.GetValue(imgSourceProperty).ToString(); } // Using a DependencyProperty as the backing store for MyProperty. This enables animation,styling,binding,etc... public static Readonly DependencyProperty imgSourceProperty = DependencyProperty.Registerattached("imgSource",typeof(string),typeof(imgSourceAttachable),new PropertyMetadata(Callback)); private static voID Callback(DependencyObject d,DependencyPropertyChangedEventArgs e) { //((button)d).source = new BitmAPImage(new Uri(Application.Current.Host.source,e.NewValue.ToString())); } }}
这是我如何在XAML中设置图像源:
<button PrismExt:imgSourceAttachable.imgSource="./Images/New.png" Style="{StaticResource ToolbarbuttonStyle}" />
有什么想法吗?
非常感谢,
<Style x:Key="ToolbarbuttonStyle" targettype="button"> <Setter Property="PrismExt:imgSourceAttachable.imgSource" Value="./Images/New.png"/> <!--...--></Style>
当绑定到附加的属性时,路径应该在括号内,所以尝试使用与TemplatedParent的relativeSource绑定
<Setter Property="Template"> <Setter.Value> <ControlTemplate targettype="button"> <Image x:name="toolbarImage" Source="{Binding relativeSource={relativeSource TemplatedParent},Path=(PrismExt:imgSourceAttachable.imgSource)}" WIDth="48" Height="48"> </Image> </ControlTemplate> </Setter.Value></Setter>
编辑:上述代码在WPF中工作,在Silverlight中,图像显示在运行时,但在设计器中出现异常。您可以使用PropertyChangedCallback中的以下代码获取映像作为解决方法
private static voID Callback(DependencyObject d,DependencyPropertyChangedEventArgs e){ button button = d as button; Image image = GetVisualChild<Image>(button); if (image == null) { RoutedEventHandler loadedEventHandler = null; loadedEventHandler = (object sender,RoutedEventArgs ea) => { button.Loaded -= loadedEventHandler; button.ApplyTemplate(); image = GetVisualChild<Image>(button); // Here you can use the image }; button.Loaded += loadedEventHandler; } else { // Here you can use the image }}private static T GetVisualChild<T>(DependencyObject parent) where T : DependencyObject{ T child = default(T); int numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++) { DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent,i); child = v as T; if (child == null) { child = GetVisualChild<T>(v); } if (child != null) { break; } } return child;}总结
以上是内存溢出为你收集整理的.net – 如何在风格中使用附加属性?全部内容,希望文章能够帮你解决.net – 如何在风格中使用附加属性?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)