【问题标题】:Dependency property not working, trying to set through style setter依赖属性不起作用,尝试通过样式设置器进行设置
【发布时间】:2010-12-08 06:56:15
【问题描述】:

我正在尝试为我新制作的用户控件设置自定义样式,但是我收到错误消息:“无法将属性 'Property' 中的值转换为 '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>

【问题讨论】:

    标签: wpf xaml styles dependency-properties


    【解决方案1】:

    我看到的最大问题是您将财产注册为Image 而不是您的UserControl。改为:

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

    如果这不起作用,则需要查看您的 XAML。

    【讨论】:

    • 这似乎已经阻止了我现在的风格中发生的错误,但是它现在阻止了我的用户控件工作,它已经从所有使用它的地方消失了。我已经添加了用户控件的 Xaml。
    【解决方案2】:

    为您的 UserControl 设置 DataContext:

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

    或者,如果你不能这样做(例如,因为 DataContext 设置为另一个对象),你可以在你的 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}}"
        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>
    

    【讨论】:

      【解决方案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
      }
      

      希望通过正确注册的依赖属性,这将帮助您缩小问题范围(甚至修复它)

      【讨论】:

      • 谢谢,我想我快到了。我不得不重新设计 ImageSource_PropertyChanged 来构建它,也许这就是它出错的地方?但是当我的按钮设置为禁用时,我的样式(我现在已在上面添加以查看)不适用于我的按钮。有任何想法吗?私人静态无效ImageSource_PropertyChanged(DependencyObject源,DependencyPropertyChangedEventArgs e){((MyButton)源).tehImage.Source =(ImageSource)e.NewValue; }
      【解决方案4】:

      在我看来,在用户控件中实现图像源的正确方法不是 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);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-01-08
        • 2016-03-28
        • 2010-12-02
        • 1970-01-01
        • 2011-05-12
        • 1970-01-01
        • 2017-05-04
        相关资源
        最近更新 更多