バインドできる値S1とS2を保持するシングルトンが必要です。目標は、値が変更されたときにいくつかのUIElementを更新することです。問題は、再利用された内の値を使用したいということですDataTemplate
。つまり、シングルトンの依存関係プロパティに直接バインドすることはできませんが、これは外部で設定する必要があります。
更新を正しく渡すには、値を。にする必要がありますDependencyProperty
。どのプロパティにバインドする必要があるかわからないため、値と同じタイプの別のアタッチ可能なプロパティAttPropertyを作成しました。S1をAttPropertyにバインドしようとしましたが、エラーが発生します。
追加情報:タイプ「TextBox」の「SetAttProperty」プロパティに「Binding」を設定することはできません。「バインディング」は、DependencyObjectのDependencyPropertyにのみ設定できます。
DependencyProperty
では、どうすれば別のアタッチメントとバインドできDependencyProperty
ますか?
これが私がこれまでに持っているシングルトン(C#)のコードです:
public class DO : DependencyObject
{
// Singleton pattern (Expose a single shared instance, prevent creating additional instances)
public static readonly DO Instance = new DO();
private DO() { }
public static readonly DependencyProperty S1Property = DependencyProperty.Register(
"S1", typeof(string), typeof(DO),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public string S1
{
get { return (string)GetValue(S1Property); }
set { SetValue(S1Property, value); }
}
public static readonly DependencyProperty AttProperty = DependencyProperty.RegisterAttached(
"Att", typeof(string), typeof(DO),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender) );
public static void SetAttProperty(DependencyObject depObj, string value)
{
depObj.SetValue(AttProperty, value);
}
public static string GetAttProperty(DependencyObject depObj)
{
return (string)depObj.GetValue(AttProperty);
}
}
問題のあるもの(XAML)は次のとおりです。
<TextBox Name="Input" Text="" TextChanged="Input_TextChanged" local:DO.AttProperty="{Binding Source={x:Static local:DO.Instance}, Path=S1}" />
アップデート
Bojin Liの変更により、エラーはなくなります。ただし、1つの問題が残っています。次のように、添付プロパティを使用してシングルトンを更新しようとすると、次のようになります。
<TextBox local:DO.Att="{Binding Source={x:Static local:DO.Instance}, Path=S1, Mode=TwoWay}" Text="{Binding Path=(local:DO.Att), RelativeSource={RelativeSource Self}, Mode=TwoWay}"/>
シングルトンで値がS1に伝播されないのはなぜですか?