如何像代理一样使用Binding?
<Setter Property="IsChecked">
<Setter.Value>
<MultiBinding>
<!-- Get value for property -->
<Binding Path="IsPressed" RelativeSource="{RelativeSource Self}" Mode="OneWay"/>
<!-- Set value to ViewModel's property -->
<Binding Path="Shift" Mode="OneWayToSource"/>
</MultiBinding>
</Setter.Value>
</Setter>
我需要使用 2 个属性绑定:一个用于获取属性值,另一个用于为 ViewModel 的属性设置值。 我怎样才能实现这个场景?
<Setter Property="IsChecked">
<Setter.Value>
<MultiBinding>
<!-- Get value for property -->
<Binding Path="IsPressed" RelativeSource="{RelativeSource Self}" Mode="OneWay"/>
<!-- Set value to ViewModel's property -->
<Binding Path="Shift" Mode="OneWayToSource"/>
</MultiBinding>
</Setter.Value>
</Setter>
I need to use 2 bindings for property: one to get value for property and one to set value to ViewModel's property.
How I can realize this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建几个附加属性。第一个将是您的绑定目标,第二个将包含您的代理的绑定。例子:
然后在 ProxySource OnChange 实现中,您将获得 TextBox 作为 UIElement,在那里您可以从 ProxySource 读取值并将其写入 ProxyTarget。
这不是一个非常干净的方法,但它应该有效。
如果你不能让它工作,我可以稍后写一个完整的示例。
好的,我已经实现了所有内容,这是完整的源代码:
以及编辑文本框时控制台的输出:
源文本:f
目标文本:f
来源:fh
目标文本:fh
来源文字:fhh
目标文本:fhh
You can create a couple of attached properties. One will be the target of your binding, and second will contain binding for your proxy. Example:
Then in ProxySource OnChange implementation you will get TextBox as UIElement, there you can read value from ProxySource and write it to ProxyTarget.
This is not a very clean aproach, but it should work.
If you can't get it working, I can write a complete sample later.
Ok, I've implemented everything, here's complete source:
And the output from console while editing textbox:
SourceText:f
TargetText:f
SourceText:fh
TargetText:fh
SourceText:fhh
TargetText:fhh
请不要围绕
IsPressed
设计您的解决方案,这实际上是一些人所说的flash
数据,这意味着它会更快变回默认值 (false)。此外,上下文绑定将具有专用的目标、源和模式。在MultiBinding
中,不支持以一种方式实现IsPressed
(从源)和另一种方式保存回另一个Target
。要进行双向更新,所有绑定都必须是TowWay
。尽管对此的Hack可以使用
MultiConverter
将Target
本身作为值之一。但强烈不推荐这样做。
Please dont design your solution around
IsPressed
, thats actually what some call aflash
data which means it changes back to a default value (false) sooner. Also contextuallyBinding
will have dedicated target, source and mode. InMultiBinding
acheiving one wayIsPressed
(from a Source) and other way saving back to anotherTarget
is not supported. For two way update to occur, all bindings have to beTowWay
.Although a Hack to this could be using
MultiConverter
having aTarget
itself as one of the values.But this is strongly NOT recommended.