FocusManager破坏了WPF数据绑定 - 为什么?

Nie*_*elW 5 data-binding wpf xaml

我花了最近几天来追踪这个bug.我的绑定被分离了,我不明白为什么.我希望我的一个文本框在我的应用程序启动时具有焦点.所以我使用了一个附加属性来设置聚焦元素.我的一些数据绑定已停止工作.

出于某种原因,只需重新安排我的XAML就会导致bug消失.

举个例子:

<StackPanel>
    <TextBox Text="{Binding Tb1}"/>
    <TextBox Text="{Binding Tb2}"/>
    <TextBox Text="{Binding Tb3}" 
           FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
    <TextBox Text="{Binding Tb4}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

Tb1,Tb2和Tb3的结合都起作用. Tb4绑定被破坏了. 如果我交换最后两行,像这样:

<StackPanel>
    <TextBox Text="{Binding Tb1}"/>
    <TextBox Text="{Binding Tb2}"/>
    <TextBox Text="{Binding Tb4}"/>
    <TextBox Text="{Binding Tb3}" 
           FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

然后所有的绑定工作得很好.

出于某种原因,在XAML中设置focus元素会导致其后的所有绑定中断.

有没有人见过这个?如果是这样,你知道为什么会这样吗?

Gle*_*mas 0

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

<StackPanel FocusManager.FocusedElement="{Binding ElementName=firstButton}">
  <Button Name="firstButton" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

也许在元素本身上设置附加属性并没有得到很好的支持。