2009-10-20 3 views
3

새로 만든 usercontrol에 대한 사용자 지정 스타일을 설정하려고하는데 오류가 발생합니다. "속성 '속성의 값을 형식의 개체로 변환 할 수 없습니다. '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); 
    } 
} 

그러나 그것은 작동하지 않았다 이미지가 표시 어쨌든 앞서 언급 한 바와 같이 같은 오류가 발생하지 않은 : 나는 또한이 시도.

아이디어가 있으십니까? 감사합니다.

- 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> 

답변

3

종속성 속성에 대한 표준 양식은 (내가 당신의 정보를 추가 한)입니다 :

public BitmapSource ImageSource 
{ 
    get { return (BitmapSource)GetValue(ImageSourceProperty); } 
    set { SetValue(ImageSourceProperty, value); } 
} 

/* Using a DependencyProperty as the backing store for ImageSource. 
    This enables animation, styling, binding, etc... */ 

public static readonly DependencyProperty ImageSourceProperty = 
     DependencyProperty.Register("ImageSource", 
      typeof(BitmapSource), 
      typeof(MyButton), 
      new UIPropertyMetadata(null) 
     ); 

"tehImage"라는 객체의 ImageSource에 종속성 속성을 전달하려고하는 것처럼 보입니다. PropertyChangedCallback을 사용하여 자동으로 업데이트하도록 설정할 수 있습니다 ... 이는 속성이 업데이트 될 때마다 자동으로 업데이트를 호출한다는 것을 의미합니다.

따라서 속성 코드가된다 :

가 올바르게 등록 된 종속성 속성과 희망
public BitmapSource ImageSource 
{ 
    get { return (BitmapSource)GetValue(ImageSourceProperty); } 
    set { SetValue(ImageSourceProperty, value); } 
} 

/* Using a DependencyProperty as the backing store for ImageSource. 
    This enables animation, styling, binding, etc... */ 

public static readonly DependencyProperty ImageSourceProperty = 
     DependencyProperty.Register("ImageSource", 
      typeof(BitmapSource), typeof(MyButton), 
      new UIPropertyMetadata(null, 
       ImageSource_PropertyChanged 
      ) 
     ); 

private static void ImageSource_PropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) 
{ 
    ((MyButton)source).tehImage.ImageSource = (ImageSource)e.NewValue 
} 

, 이것은 당신이 문제의 범위를 좁히는 데 도움이됩니다 (또는 그것을 해결)

+0

고마워, 나는 거의 다 왔다고 생각해. ImageSource_PropertyChanged를 다시 작성하여 빌드하고 어쩌면 이것이 잘못 될 수 있을까요? 하지만 내 스타일 (내가보기 위해 위에 추가 한 기능)이 비활성화되었을 때 내 버튼에 적용되지 않습니다. 어떤 아이디어? private static void ImageSource_PropertyChanged (DependencyObject source, DependencyPropertyChangedEventArgs e) { ((MyButton) 소스) .tehImage.Source = (ImageSource) e.NewValue; } – 4imble

4
내가 볼

가장 큰 문제는 Image가 아닌 소유 당신이 재산을 등록하고 있다는 것입니다 귀하의 UserControl. 변경 :

public static readonly DependencyProperty ImageSourceProperty = 
      DependencyProperty.Register("ImageSource", typeof(BitmapSource), typeof(MyButton)); 

그래도 작동하지 않으면 XAML을 확인해야합니다.

+0

지금 내 스타일에서 오류가 발생하는 것을 중지 한 것으로 보이지만 이제는 내 사용자 컨트롤이 일하면서, 그것이 사용 된 모든 장소에서 사라졌습니다. 나는 usercontrol의 Xaml을 추가했다. – 4imble

1

당신의 UserControl의 DataContext를 설정 : (DataContext를 예를 들어, 다른 객체로 설정되어 있기 때문에) 당신이 할 수없는 경우, 당신은 당신의 XAML에서이 작업을 수행 할 수

public MyButton() 
{ 
    InitializeComponent(); 
    DataContext = this; 
} 

또는 :

<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}}" 
    x:Name="MyControl"> 


    <Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick"> 

     <Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" > 
      <Grid> 
       <Image Name="tehImage" Source="{Binding ElementName=MyControl, Path=ImageSource}" /> 
       <TextBlock Name="tehText" Text="{Binding ElementName=MyControl, Path=Text}" Style="{DynamicResource ButtonText}" /> 
      </Grid> 
     </Border> 

    </Button> 
</UserControl> 
0

소스를 구현하는 올바른 방법을 내 의견으로는 사용자 정의 컨트롤의 Image가 BitmapSouce가 아닙니다. 가장 쉽고 좋은 방법은 우리에게 Uri를 사용하는 것입니다.이것에

ImageSourceProperty = DependencyProperty.Register(
    "ImageSource", typeof (Uri), typeof (MyButton), 
    new FrameworkPropertyMetadata(new PropertyChangedCallback(OnImageSourceChanged))); 

및 재산 : (또한 변경 콜백 이벤트를 정의하는 동안)

이에 종속성 속성을 변경

public Uri ImageSource 
{ 
    get 
    { 
      return (Uri)GetValue(ImageSourceProperty); 
    } 
    set 
    { 
      SetValue(ImageSourceProperty, value); 
    } 
} 

전화는 다시 다음과 같이 인 경우 :

private static void OnImageSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
{ 
    MyButton hsb = (MyButton)sender; 

    Image image = hsb.tehImage; 
    image.Source = new BitmapImage((Uri) e.NewValue); 
} 
관련 문제