我想为我新建的用户控件设置一个自定义样式,但是我收到错误:“无法将属性'属性'中的值转换为类型的对象'System.Windows.DependencyProperty'。”依赖属性不工作,试图通过样式设置器
我想我已经建立了依赖属性,但它似乎不是这种情况,所以我做了一些研究,并补充说:
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(BitmapSource), typeof(Image));
,使这个: - MyButton.Xaml.Cs -
namespace Client.Usercontrols
{
public partial class MyButton : UserControl
{
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(BitmapSource), typeof(Image));
public MyButton()
{
InitializeComponent();
}
public event RoutedEventHandler Click;
void onButtonClick(object sender, RoutedEventArgs e)
{
if (this.Click != null)
this.Click(this, e);
}
BitmapSource _imageSource;
public BitmapSource ImageSource
{
get { return _imageSource; }
set
{
_imageSource = value;
tehImage.Source = _imageSource;
}
}
}
}
这不幸的是不起作用。我也试过这个:
public BitmapSource ImageSource
{
get { return (BitmapSource)GetValue(MyButton.ImageSourceProperty); }
set
{
SetValue(ImageSourceProperty, value);
}
}
但是,这并没有工作,图像没有显示,并产生与前面提到的相同的错误。
任何想法? 尊敬Kohan。
- MyButton.Xaml -
<UserControl x:Class="Client.Usercontrols.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">
<Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
<Grid>
<Image Name="tehImage" Source="{Binding ImageSource}" />
<TextBlock Name="tehText" Text="{Binding Text}" Style="{DynamicResource ButtonText}" />
</Grid>
</Border>
</Button>
</UserControl>
- myButton的风格 -
<Style TargetType="{x:Type my:MyButton}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type my:MyButton}">
<ContentPresenter />
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="ImageSource" Value="../Images/Disabled.png" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
谢谢,我想我快到了。我不得不重新修改ImageSource_PropertyChanged来构建它,也许这是它出错的地方?但我的样式(我现在已添加上面看到)不适用于我的按钮,当它被设置为禁用。有任何想法吗? private static void ImageSource_PropertyChanged(DependencyObject source,DependencyPropertyChangedEventArgs e) {((MyButton)source).tehImage.Source =(ImageSource)e.NewValue; } – 4imble 2009-10-21 11:57:54