我创建了一个包含依赖项属性“文本”的自定义TextBox控件(但不是从TextBox派生的)。如何在TwoWay绑定中传递来自源的更改?
我已经添加了这个实例并将其绑定到我的视图模型上的一个属性使用TwoWay绑定。
从我的自定义TextBox控件中,如何以更改传播到视图模型属性的方式更新Text属性?
如果我在我的自定义控件上设置了“Text”属性,则将离开视图模型上的属性的绑定替换为null。
我还以为这将是简单的,但我看不出如何做到这一点(标准TextBox控件必须这样做!)
干杯
编辑:
自定义控件:
public class SampleCustomControl : CustomControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(SampleCustomControl), new PropertyMetadata(null));
public void Update()
{
// This replaces my binding, I want it to pass the new value
// through to the "SomeProperty" two way binding.
Text = "some value";
}
}
用法:
<Controls:SampleCustomControl Text="{Binding SomeProperty, Mode=TwoWay}" />
所有DependencyProperty更新都通过SetValue在幕后触发绑定上的更改事件。你通常会添加一个set/get对到你的DP(这只是为你自己使用),它也调用GetValue/SetValue。你可以显示你的XAML和代码的控制和使用,因为它应该是微不足道的。设置你的文本属性不应该改变绑定。 –
我正在设置一个Text属性,它自己调用了SetValue方法,但是这正在替换绑定 - 我将添加一些代码来演示它 –