我想爲我新建的用戶控件設置一個自定義樣式,但是我收到錯誤:「無法將屬性'屬性'中的值轉換爲類型的對象'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