Объект типа «System.Windows.Data.Binding» не может быть преобразован в тип «System.String» - PullRequest
4 голосов
/ 23 мая 2011

Интересно, кто-нибудь может помочь? Я уже пол дня бьюсь головой об эту проблему, должно быть, я что-то делаю не так. У меня есть пользовательский элемент управления с рядом свойств зависимостей.

[TemplatePart(Name = InformationBubble.InformationBubbleTitlePart, Type = typeof(TextBlock))]
[TemplatePart(Name = InformationBubble.InformationBubbleProductImagePart, Type=typeof(Image))]

public class InformationBubble : Control 
{
    #region Template Parts Name Constants

    /// <summary>
    /// Name constant for the Information Bubble Title Part
    /// </summary>
    public const string InformationBubbleTitlePart = "InformationBubbleTitleText";

    /// <summary>
    /// Name constant for the Information Bubble Product Image Part
    /// </summary>
    public const string InformationBubbleProductImagePart = "InformationBubbleProductImage";

    #endregion

    #region TemplateParts

    private TextBlock _Title;

    internal TextBlock Title
    {
        get { return _Title; }
        private set
        {
            _Title = value;

            if (_Title != null)
            {
                _Title.Text = this.ProductTitleText;       
            }
        }
    }

    private Image _ProductImage;

    internal Image ProductImage
    {
        get { return _ProductImage; }
        private set
        {
            _ProductImage = value;

            if (_ProductImage != null)
            {
                _ProductImage.Source = this.ProductImageSource;
            }
        }
    }

    #endregion

    #region Public String Product Title 

    // Dependency properties declaration
    public static readonly DependencyProperty ProductTitleProperty = DependencyProperty.Register(
        "ProductTitle",
        typeof(string),
        typeof(InformationBubble),
        new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnProductTitleChanged)));

    public static void OnProductTitleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        InformationBubble iBubble = sender as InformationBubble;

        if (iBubble.Title != null)
        {
            iBubble.Title.Text = e.NewValue as string;
        }
    }

    public string ProductTitleText
    {
        get { return GetValue(ProductTitleProperty) as string; }
        set { SetValue(ProductTitleProperty, value); }
    }

    #endregion

    #region Public Image Source Product Image

    public static readonly DependencyProperty ProductImageSourceProperty = DependencyProperty.Register(
        "ProductImageSource",
        typeof(ImageSource),
        typeof(InformationBubble),
        new PropertyMetadata(null, new PropertyChangedCallback(OnProductImageSourceChanged)));

    public static void OnProductImageSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        InformationBubble iBubble = sender as InformationBubble;

        if (iBubble.ProductImage != null)
        {
            iBubble.ProductImage.Source = e.NewValue as ImageSource;
        }
    }

    public ImageSource ProductImageSource
    {
        get { return GetValue(ProductImageSourceProperty) as ImageSource; }
        set { SetValue(ProductImageSourceProperty, value); }
    }

    #endregion

    public InformationBubble()
    {
         this.DefaultStyleKey = typeof(InformationBubble);
    }

    #region Overrides

    public override void OnApplyTemplate()
    {       
        base.OnApplyTemplate();

        Title = GetTemplateChild(InformationBubble.InformationBubbleTitlePart) as TextBlock;
        ProductImage = GetTemplateChild(InformationBubble.InformationBubbleProductImagePart) as Image;
    }

    #endregion

    #region Private Methods

    private void GoToState(string stateName, bool useTransitions)
    {
        VisualStateManager.GoToState(this, stateName, useTransitions);
    }

    #endregion
}

Теперь, если я использую этот элемент управления где-нибудь в моем xaml, он работает, если я делаю это:

<controls:InformationBubble 
        ProductImageSource="{Binding SelectedItem.NormalImageSource}"
        ProductTitleText="Test Title"
        "/>

Но если я попытаюсь, и данные свяжут текст заголовка продукта со свойством title объекта SelectedItem в моей модели представления:

<controls:InformationBubble 
            ProductImageSource="{Binding SelectedItem.NormalImageSource}"
            ProductTitleText="{Binding SelectedItem.Title, Mode=TwoWay"
            "/>

Я получаю Объект типа «System.Windows.Data.Binding» не может быть преобразован в тип «System.String». Свойство text объекта TextBlock является DependencyProperty, поэтому я должен упустить что-то очевидное здесь.

Любая помощь или понимание очень ценится.

Крис

1 Ответ

7 голосов
/ 23 мая 2011

Может быть, имя объекта неверно.Может ли «ProductTitle» в приведенном ниже коде быть «ProductTitleText»?

public static readonly DependencyProperty ProductTitleProperty = DependencyProperty.Register(
    "ProductTitle",  // "ProductTitleText" ?
    typeof(string),
    typeof(InformationBubble),
    new PropertyMetadata(string.Empty, new PropertyChangedCallback(OnProductTitleChanged)));

Я полагаю, что при использовании строковой константы WPF использует отражение для прямого доступа к свойству «public string ProductTitleText».DependencyProperty игнорируется, так как имя свойства не совпадает («ProductTitle» и «ProductTitleText»).

Таким образом, для заголовка у вас есть свойство зависимости с именем «ProductTitle» и свойство (string)называется «ProductTitleText».Для ProductImage у вас есть свойство зависимости, называемое «ProductImageSource», и свойство (типа ImageSource), также называемое «ProductImageSource».

Имеет ли это смысл?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...