提问人:Josh 提问时间:7/28/2023 最后编辑:Josh 更新时间:7/28/2023 访问量:36
WPF 组合框和文本框行为
WPF Combobox & Textbox Behavior
问:
我做了一个简单的测试,试图找出我在组合框中遇到的问题。我想让用户有机会在触发计算之前取消对控件所做的编辑。
在测试中,一个文本框给了我想要的结果。取消时,控件将恢复到原来的状态。取消组合框中的输入时,组合框看起来好像没有取消。在这两种情况下,模型和视图模型都是正确的。
如何让组合框的行为方式与文本框的行为方式相同,以允许控件正确反映视图模型?
模型和视图模型:
Option Explicit On
Option Strict On
Imports System.ComponentModel
Public Class ViewModel
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub OnPropertyChanged(propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Public Sub New()
Model = New Model
End Sub
Public Property Model As Model
Public Property Text As String
Get
Return Model.Text
End Get
Set(value As String)
If cancel() Then
OnPropertyChanged("Text")
Exit Property
End If
Model.Text = value
OnPropertyChanged("Text")
End Set
End Property
Private Function cancel() As Boolean
If MsgBox("Cancel?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Return True
Else Return False
End If
End Function
End Class
Public Class Model
Public Sub New()
Text = "Hello, World!"
End Sub
Public Property Text As String
End Class
视图:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:test"
mc:Ignorable="d"
Title="MainWindow" Height="241" Width="416" d:DataContext="{d:DesignInstance Type=local:ViewModel}">
<Grid>
<TextBox HorizontalAlignment="Left" Margin="108,95,0,0" TextWrapping="Wrap" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
<ComboBox HorizontalAlignment="Left" Margin="108,144,0,0" VerticalAlignment="Top" Width="120" IsEditable="True" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
窗口代码隐藏:
Class MainWindow
Public Sub New()
InitializeComponent()
DataContext = New ViewModel
End Sub
End Class
答:
1赞
Songpl
7/28/2023
#1
因为 包含 ,当用户 时,它不会影响 ,这就是发生此问题的原因。ComboBox
TextBox
Cancel()
TextBox.Text
我们可以添加一个 和 在其事件中,获取 、 和 的属性。Button
Click
Text
Model
ComboBox
TextBox
ComboBox
我正在使用 C#,我相信您应该能够理解。
// in Button click event
// get TextBox inside the ComboBox
var textBox = cb.Template.FindName("PART_EditableTextBox", cb) as TextBox;
MessageBox.Show($"model: {Model.Text}, cb: {cb.Text}, textBox: {textBox.Text}");
我用这种方法解决了这个问题。你可以试一试。
<ComboBox x:Name="cb" IsEditable="True" Text="{Binding Path=Text, Delay=5}" />
评论
0赞
Josh
7/29/2023
感谢您的见解。增加延迟是一个完美而简单的解决方案。
评论