我想拥有一个持有一些值的单身人士S1和S2我可以绑定到。目标是在其值更改时更新一些UIElements。问题是我想使用重用的DataTemplate
中的值。这意味着我不能直接绑定到单例的依赖属性,但必须在外部设置。如何将一个`DependenyProperty`绑定到另一个可附加的`DependencyProperty`?
要正确传递更新,值必须是DependencyProperty
。因为我不知道我必须绑定哪个属性,所以我创建了另一个与数值相同类型的可附加属性AttProperty。现在,我试图绑定S1到AttProperty但是这给了我一个错误:
Additional information: A 'Binding' cannot be set on the 'SetAttProperty' property of type 'TextBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
那么,如何可以绑定可连接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}" />
更新
随着博金利的变化错误消失了。但是,一个问题仍然是 - 如果我现在尝试用这样的附加属性的帮助来更新单:
<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?
这仍然不会更新单身的情况下,在文本框中的值更改。如果我正确理解这一点,Att不会改变,但它包含的属性S1。如果我想用绑定重新设置Att,则会触发一个事件。或者我对更新机制有错误的理解? – Pascal 2012-04-27 09:28:11
在建议的代码中,'onAttChanged'希望'DependencyObject'成为'DO'。但是'Att'没有设置在单例'DO'上,而是连接到其他元素 - 在这个例子中是一个TextBox。所以我想这永远不会成功。 – Pascal 2012-04-27 11:06:25
在这种情况下,应该无关紧要,因为依赖项更新应该触发。当你说S1没有改变时,你如何检查。您是否期望更新为文本更改(即用户输入)或失去焦点(这是默认设置) – 2012-04-27 11:12:00