FocusManager破坏了WPF数据绑定-为什么? [英] WPF data bindings being broken by FocusManager - WHY?

查看:63
本文介绍了FocusManager破坏了WPF数据绑定-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近几天,我一直在跟踪该错误.我的绑定被拆开了,我也不知道为什么.我希望当我的应用程序启动时,我的一个文本框具有焦点.因此,我使用了一个附加属性来设置焦点元素.我的某些数据绑定停止工作.

I've spent the last several days tracking down this bug. My bindings were being detached, and I had no idea why. I want one of my textboxes to have focus when my application starts. So I used an attached property that sets the focused element. Some of my data bindings stopped working.

由于某种原因,只是重新安排我的XAML导致该错误消失了.

For some reason, simply re-arranging my XAML caused the bug to go away.

以这个例子为例:

<StackPanel>
    <TextBox Text="{Binding Tb1}"/>
    <TextBox Text="{Binding Tb2}"/>
    <TextBox Text="{Binding Tb3}" 
           FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
    <TextBox Text="{Binding Tb4}"/>
</StackPanel>

Tb1,Tb2和Tb3的绑定都起作用. Tb4绑定已断开.如果我交换最后两行,如下所示:

The bindings for Tb1, Tb2 and Tb3 all work. The Tb4 binding is broken. If I swap the last two lines, like this:

<StackPanel>
    <TextBox Text="{Binding Tb1}"/>
    <TextBox Text="{Binding Tb2}"/>
    <TextBox Text="{Binding Tb4}"/>
    <TextBox Text="{Binding Tb3}" 
           FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
</StackPanel>

然后所有绑定都可以正常工作.

then all the bindings work just fine.

由于某些原因,在XAML中设置焦点元素会导致其后的所有绑定中断.

还有其他人看到过吗?如果是这样,您知道为什么会这样吗?

Has anyone else seen this? If so, do you know why this happens?

推荐答案

我认为使用 FocusManager.FocusedElement 的正确方法是在视觉树中较高的元素上设置附加属性:

I think the correct way to use FocusManager.FocusedElement is to set the attached property on an element higher in the visual tree:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=firstButton}">
  <Button Name="firstButton" />
</StackPanel>

可能无法很好地支持在元素本身上设置附加属性.

Maybe setting the attached property on the element itself is not well supported.

这篇关于FocusManager破坏了WPF数据绑定-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆