1

一部のイベントに応じてソースを操作する必要があるため、カスタム Image コントロールを作成しようとしています。また、そのようなコントロールのかなり大きな配列も必要です。そのために、クラス (「nfImage」) を Image から継承することを決定し、ビューモデルにバインドできる DP (実際にはイベントを反映する) が必要です。私がやっている:

class nfImage : Image
{
    public static readonly DependencyProperty TagValueProperty =
        DependencyProperty.Register("TagValue", typeof(int), typeof(nfImage), new UIPropertyMetadata(0));

    public int TagValue
    {
        get { return (int)GetValue(TagValueProperty); }
        set
        {
            SetValue(TagValueProperty, value);
            if (this.Source != null)
            {
                string uri = (this.Source.ToString()).Substring(0, (this.Source.ToString()).Length - 5) + value.ToString() + ".gif";
                ImageBehavior.SetAnimatedSource(this, new BitmapImage(new Uri(uri, UriKind.Absolute)));
            }
        }
    }
}

問題は、それが機能しないことです。コード ビハインドから TagValue の値を設定している場合、ソースは変更されますが、(dp を介して) xaml から設定している場合は何も起こらず、バインディングも機能しません。どうすればこれを達成できますか?

4

2 に答える 2

2

XAML は直接呼び出さないため、セッターを使用することはできません。セッターを経由せずに SetValue(DependencyProperty, value) を呼び出すだけです。PropertyChanged イベントを処理する必要があります。

class nfImage : Image
{

    public static readonly DependencyProperty TagValueProperty =
        DependencyProperty.Register("TagValue", typeof(int), typeof(nfImage), new UIPropertyMetadata(0, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        var _this = dependencyObject as nfImage;
        var newValue = dependencyPropertyChangedEventArgs.NewValue;
        if (_this.Source != null)
        {
            string uri = (_this.Source.ToString()).Substring(0, (_this.Source.ToString()).Length - 5) + newValue.ToString() + ".gif";
            //ImageBehavior.SetAnimatedSource(this, new BitmapImage(new Uri(uri, UriKind.Absolute)));
        }
    }

    public int TagValue
    {
        get { return (int)GetValue(TagValueProperty); }
        set { SetValue(TagValueProperty, value); }
    }
}
于 2013-02-11T22:08:04.083 に答える
1

DependencyPropertyのラッパープロパティは単なる定型文であり、GetValueとSetValue以外は何も実行しないでください。この理由は、コードからプロパティラッパーへの直接呼び出し以外で値を設定する場合は、ラッパーを使用せず、GetValueとSetValueを直接呼び出すためです。これには、XAMLとバインディングが含まれます。ラッパーセッターの代わりに、DP宣言のメタデータにPropertyChangedコールバックを追加し、そこで追加の作業を行うことができます。これは、SetValue呼び出しに対して呼び出されます。

于 2013-02-11T22:09:30.150 に答える