文本框文本绑定在样式触发器中损坏

Textbox Text Binding Broken in Style Trigger

我有一个如下定义的文本框。这样做是为了处理当 UpdateSourceTrigger 为 PropertyChanged(逐个字符验证需要)时在 .NET 4+ 中发生的搞砸编辑。

问题。当我在 TextBox 中输入文本时,它很好。一旦失去焦点,文本框就会变成空白。当我将光标移回时 - 之前输入的数字又回来了。如果我在代码中设置断点,那么 Item.amount 和 drvi.item("amount") 都是正确的。

        <TextBox x:Name="txtAmount" Margin="170,35,0,0" Width="150" Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource RoundedTextBox}">
                    <Setter Property="Text">
                        <Setter.Value>
                            <Binding Path="Item.amount" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type l:ItemView}}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" StringFormat="#,##0.00">
                                <Binding.ValidationRules>
                                    <l:CurrencyRule />
                                </Binding.ValidationRules>
                            </Binding>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="IsKeyboardFocusWithin" Value="True">
                            <Setter Property="Text">
                                <Setter.Value>
                                    <Binding Path="Item.amount" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type l:ItemView}}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                                        <Binding.ValidationRules>
                                            <l:CurrencyRule />
                                        </Binding.ValidationRules>
                                    </Binding>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

底层绑定如下class

Private _Item As DataRowView
Public Property Item As DataRowView
    Get
        Return _Item
    End Get
    Set(value As DataRowView)
        _Item = value
        NotifyPropertyChanged("Item")
    End Set
End Property

设置为等于 DataRowView:

strSelect = "SELECT * FROM Items WHERE ID=0"
dsicmd = New OleDbDataAdapter(strSelect, cn)
dsi.Clear()
dsicmd.Fill(dsi, "Item")
dvi = New DataView(dsi.Tables.Item("Item"))
drvi = dvi.AddNew                    
Item = drvi

感谢所有帮助。 谢谢 安迪

看起来答案与 DataView.AddNew 有关。如果我如下创建新行,它就可以正常工作。不知道为什么真的。调试绑定看起来像 .AddNew 没有正确设置默认字段值。

strSelect = "SELECT * FROM Items WHERE ID=0"
dsicmd = New OleDbDataAdapter(strSelect, cn)
dsi.Clear()
dsicmd.Fill(dsi, "Item")
dsi.Tables("Items").Rows.Add()
dvi = New DataView(dsi.Tables.Item("Item"))
drvi = dvi(0)