WPF - 文本框设置为只读时未正确绑定
WPF - TextBox not binding properly when set to readonly
我有 TextBox,我用它来将文件路径添加(仅添加而不读取)到数据库中。当用户选择特定文件 (OpenFileDialog) 时设置文本 属性。所以,我将它设置为只读状态,它不会正确绑定。当我删除只读时它工作正常。
<Button Name="btnAddFile" Content="+" HorizontalAlignment="Left" Width="23" Height="23" Click="AddFilePath"/>
<TextBox Name="tbxFilePath" Height="23" Text="{Binding FilePath}" Width="364" IsReadOnly="True"/>
当我使用时:
Text="{Binding FilePath, Mode=OneWayToSource}"
它有时有效,但大多数时候无效 (?!)。我可以使用 TextBlock 或 Label,但我真的很想了解发生了什么并使用 TextBox。
我正在使用 Entity Framework,但我认为这无关紧要。
问题:如何以编程方式将文本添加到只读的 TextBox 控件并能够绑定它。
编辑:我知道问题出在哪里了。当我将焦点放在 TextBox after 上时,我从代码隐藏中将其设置为 Text 属性,它起作用了。我想当我从代码隐藏中执行它时,它必须通知文本已更改。怎么做?
您是否尝试过使用 OneWay
绑定?
MSDN 读取:
OneWay Updates the binding target (target) property when the binding source (source) changes. This type of binding is appropriate if the control being bound is implicitly read-only.
我认为这涵盖了您的情况。
target 是您的文本框 Text
属性 而您的 source 是您的 FilePath
属性 在您的 ViewModel 上。
使用:
Text="{Binding FilePath, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
编辑
此答案假设您已在 ViewModel 上实施 INotifyPropertyChanged
。
编辑
正确的绑定方式是OneWayToSource
。由 OP 确认。
我有 TextBox,我用它来将文件路径添加(仅添加而不读取)到数据库中。当用户选择特定文件 (OpenFileDialog) 时设置文本 属性。所以,我将它设置为只读状态,它不会正确绑定。当我删除只读时它工作正常。
<Button Name="btnAddFile" Content="+" HorizontalAlignment="Left" Width="23" Height="23" Click="AddFilePath"/>
<TextBox Name="tbxFilePath" Height="23" Text="{Binding FilePath}" Width="364" IsReadOnly="True"/>
当我使用时:
Text="{Binding FilePath, Mode=OneWayToSource}"
它有时有效,但大多数时候无效 (?!)。我可以使用 TextBlock 或 Label,但我真的很想了解发生了什么并使用 TextBox。
我正在使用 Entity Framework,但我认为这无关紧要。
问题:如何以编程方式将文本添加到只读的 TextBox 控件并能够绑定它。
编辑:我知道问题出在哪里了。当我将焦点放在 TextBox after 上时,我从代码隐藏中将其设置为 Text 属性,它起作用了。我想当我从代码隐藏中执行它时,它必须通知文本已更改。怎么做?
您是否尝试过使用 OneWay
绑定?
MSDN 读取:
OneWay Updates the binding target (target) property when the binding source (source) changes. This type of binding is appropriate if the control being bound is implicitly read-only.
我认为这涵盖了您的情况。
target 是您的文本框 Text
属性 而您的 source 是您的 FilePath
属性 在您的 ViewModel 上。
使用:
Text="{Binding FilePath, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
编辑
此答案假设您已在 ViewModel 上实施 INotifyPropertyChanged
。
编辑
正确的绑定方式是OneWayToSource
。由 OP 确认。